简体   繁体   中英

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. I now want to define these strings into "dates" using datetime.strptime so that I then can use datetime.strftime to format them.

the dates that are within dates_2 are these: 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" %

ValueError: time data ' 26/09/2021' does not match format '%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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM