[英]Says that I date formatting does not match. Also, how can I format these dates into year/month/date (python)
So I have a list of dates that I turned into a string called dates_2.所以我有一个日期列表,我把它变成了一个名为 dates_2 的字符串。 I now want to define these strings into "dates" using datetime.strptime so that I then can use datetime.strftime to format them.
我现在想使用 datetime.strptime 将这些字符串定义为“日期”,这样我就可以使用 datetime.strftime 来格式化它们。
the dates that are within dates_2 are these: 26/09/2021 04/12/2021 13/02/2022 11/11/2021 13/12/2022 dates_2 内的日期如下: 26/09/2021 04/12/2021 13/02/2022 11/11/2021 13/12/2022
import datetime as dt
from datetime import datetime
#Dates
dates = re.findall(r"[0-9]+/[0-9]+/[0-9]+", txt)
dates_2 = ""
for x in dates:
dates_2 += ' '+ x
dates_3 = datetime.strptime(dates_2, '%d/%m/%Y')
dates_sorted = datetime.strftime('%Y/%m/%d')
print("Dates:", dates_sorted)
The errors that I get are these:我得到的错误是:
raise ValueError("time data %r does not match format %r" % raise ValueError("时间数据 %r 与格式 %r 不匹配" %
ValueError: time data ' 26/09/2021' does not match format '%d/%m/%Y' ValueError:时间数据“26/09/2021”与格式“%d/%m/%Y”不匹配
Any help would be really appreciated!任何帮助将非常感激!
You need to remove the whitespace:您需要删除空格:
ValueError: time data ' 26/09/2021' does not match format '%d/%m/%Y'
The pattern does not match your string, because the string starts with a whitespace.该模式与您的字符串不匹配,因为该字符串以空格开头。 Call
.strip()
on your string before passing it to the datetime
functions.在将字符串传递给
datetime
时间函数之前调用.strip()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.