【问题标题】:How do I remove the 00:00:00 from my string如何从我的字符串中删除 00:00:00
【发布时间】:2019-03-28 19:34:47
【问题描述】:

我正在尝试使用 pandas 从我的链接中删除 00:00:00(HH:MM:SS)。

https://www.z-ratos.com/orical/?from=USD&amount=0&date=2018-10-24 00:00:00

那么我如何从我的链接中删除这个 00:00:00 以使其正常工作。 我试过这段代码:

import requests
import pandas as pd
from datetime import *

# TO TAKE DATE DIFFERENCE IN LIST
today = datetime.today()
dates = pd.date_range('2018-10-13', today)
#print(dates)

for i in dates:
    #print(i)
    url = 'https://www.z-ratos.com/orical/?from=USD&amount=0&date%s'%i
    print(url)

即将输出的是:

https://www.z-ratos.com/orical/?from=USD&amount=0&date=2018-10-24 00:00:00
    .....
     ......
      ......

要求的输出是:

https://www.z-ratos.com/orical/?from=USD&amount=0&date=2018-10-24

所以请帮忙 在此先感谢...

【问题讨论】:

  • string.split()怎么样?

标签: python string pandas date


【解决方案1】:

使用strftime("%Y-%m-%d")

例如:

import requests
import pandas as pd
from datetime import *

# TO TAKE DATE DIFFERENCE IN LIST
today = datetime.today()
dates = pd.date_range('2018-10-13', today)
#print(dates)

for i in dates:
    #print(i)
    url = 'https://www.z-ratos.com/orical/?from=USD&amount=0&date%s'%i.strftime("%Y-%m-%d")
    print(url)

【讨论】:

    【解决方案2】:

    对字符串使用DatetimeIndex.strftime

    dates = pd.date_range('2018-10-13', today).strftime('%Y-%m-%d')
    

    然后是formatf-strings

    for i in dates:
        #print(i)
        url = 'https://www.z-ratos.com/orical/?from=USD&amount=0&date={}'.format(i)
        #python 3.6+ solution
        #url = f'https://www.z-ratos.com/orical/?from=USD&amount=0&date={i}'
        print(url)
    

    【讨论】:

    • @royal - 是的,当然,在我看来更好的是使用formatf-strings,如%s,检查this link
    • 谢谢,但一个答案就足够了。帮我一个忙,并添加一些关于在 f 字符串中使用格式化代码的信息。或者在str.format 内也是如此。 '{:%Y-%m-%d}'.format(i) 应该也可以。
    【解决方案3】:

    使用Datetime 对象的date 方法。要从所有日期中删除时间戳:

    dates = [d.date() for d in dates]
    

    当您遍历日期时,或者只使用i.date()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 2020-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多