Depending on whether the item is over a week old or not, the date comes in the following formats:
Less than a week old comprised of day of the week and time:
date1 = "Monday 21:14"
More than a week old, is just the date:
date2 = "5 Apr '21"
I read them in as a string and need to parse them both to a consistent timestamp.
One way I tried is:
from dateutil.parser import parse
parse(date1)
# output: datetime.datetime(2021, 4, 23, 22, 18)
parse(date2)
# output: datetime.datetime(2021, 4, 5, 0, 0)
Using the dateutil
package I can get it to easily parse date2
, but it gives me the forward looking friday for date1
not the previous friday.
How would you suggest I parse the two dates, without knowing which will be received? and can I instruct the parser to take the last previous weekday (i.e. previous friday)
Many thanks
Setting a default for the parser might work. Since you want to take the last previous weekday in case the day of the month is not defined, you can use today's date one week ago.
Ex:
from datetime import datetime, timedelta
from dateutil import parser
date1 = "Monday 21:14"
date2 = "5 Apr '21"
# reference = date of today one week ago (as datetime object):
ref_date = datetime(*datetime.now().timetuple()[:3]) - timedelta(7)
for d in (date1, date2):
print(parser.parse(d, default=ref_date))
# 2021-04-12 21:14:00
# 2021-04-05 00:00:00
Note that today is Monday 2021-4-19 but this code gives you the previous Monday, 2021-4-12.