Reputation: 2605
I have an array of dates that is formatted like so:
['October 22nd, 2019', 'February 8th, 2020', 'July 31st, 2020', 'September 21st, 2020', ...]
I'd like to turn it into datetime objects using strptime, but I can't figure out how to hand the spelled out parts of the days, e.g. 22nd
or 8th
and it doesn't say in the format documentation.
The following works when there's no written out part of the day:
from datetime import datetime
dt_obj = datetime.striptime('October 22, 2019', '&B &d, &Y')
But I can't figure out how to parse a string that has the day written out:
in: dt_obj = datetime.striptime('October 22nd, 2019', '&B &d, &Y')
out: ValueError: time data 'October 22nd, 2019' does not match format '%B %d, %Y'
What's the proper format for this? Thank you!
Upvotes: 1
Views: 159
Reputation: 18446
e.g.
22nd
or8th
and it doesn't say in the format documentation
You got it right, it is not mentioned in documentation because there is no such formats, one way you can parse them is by using regex
, and converting those date strings to something for which Python's datetime
has the format for.
import re
from datetime import datetime
[datetime.strptime(x, '%B %d %Y') for x in [' '.join(re.findall('^\w+|\d+',each)) for each in ['October 22nd, 2019', 'February 8th, 2020', 'July 31st, 2020', 'September 21st, 2020']]]
#output:
[datetime.datetime(2019, 10, 22, 0, 0), datetime.datetime(2020, 2, 8, 0, 0), datetime.datetime(2020, 7, 31, 0, 0), datetime.datetime(2020, 9, 21, 0, 0)]
Upvotes: 1