python strptime ignoring %A?

Viewed 83

I have some arbitrary-week times in the following format: "Monday 11:30am"

I would like to parse these into datetime.datetimes. I don't care what year/month/day I end up with in the object, but if the string says "Monday", then the resulting datetime.datetime should be a day that is a Monday.

Unfortunately, the %A formatter (day of week) seems to be ignored by strptime:

>>> import datetime
>>> a = "Monday 11:30am"
>>> b = "Tuesday 11:30am"
>>> dt_format = "%A %I:%M%p"
>>> datetime.datetime.strptime(a, dt_format)
datetime.datetime(1900, 1, 1, 11, 30)
>>> datetime.datetime.strptime(b, dt_format)
datetime.datetime(1900, 1, 1, 11, 30)

How do I correctly parse the day of the week?

1 Answers

It seems that datetime is not picking up a date correctly when only specifying the day of the week.

Since you do not care what year/month/day you end up with, you can use the current week number of the year. When combined with the day and week number, datetime will output a date correctly.


import datetime
import calendar

rand_date = datetime.datetime.strftime(datetime.datetime.today(), '%U %Y ')
dt_format = "%U %Y %A %I:%M%p"

a = "Monday 11:30am"
b = "Tuesday 11:30am"

print(datetime.datetime.strptime(rand_date + a, dt_format))
print(calendar.day_name[datetime.datetime.strptime(rand_date + a, dt_format).weekday()])

print(datetime.datetime.strptime(rand_date + b, dt_format))
print(calendar.day_name[datetime.datetime.strptime(rand_date + b, dt_format).weekday()])

2021-02-22 11:30:00
Monday
2021-02-23 11:30:00
Tuesday
Related