简体   繁体   English

说我的日期格式不匹配。 另外,如何将这些日期格式化为年/月/日(python)

[英]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.

相关问题 如何将此日期格式化为日 - 月 - 年 - How can I format this date into Day - Month - Year 如何比较 python 中的日期? 我有月份日期年份格式并想与当前日期(7 天内)进行比较 - How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days) 如何将星期几、月份、日期转换为年 - 月 - 日期 - How can I convert day of week, Month, Date to Year - Month - Date 如何在Python中按月逐月绘制日期值的直方图? - How can I draw the histogram of date values group by month in each year in Python? 如何将日期从日-月-年重新格式化为年-月-日? - How can I reformat date from day-month-year to year-month-day? 如何将日,月,年转换为日期格式? - How to convert day,month,year into date format? 如何解析没有零填充的日期,格式为(1 位或 2 位年份)-(月份缩写)? - How do I parse a date without zero padding, in the format (1 or 2-digit year)-(Month abbreviation)? 如何在pyspark数据帧中将多列即时间、年、月和日期转换为日期时间格式 - How to convert multiple columns i.e time ,year,month and date into datetime format in pyspark dataframe Python正则表达式不匹配。 我不能应付 - Python regex does not match. I cant handle it 如何使用Python / Pandas从“日期”字段按月分组 - How can I Group By Month from a Date field with Python/Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM