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!
CodePudding user response:
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.
