dateutil.parser.parse to get end of month if passing in mm/yyyy, otherwise return exactly date when passing in dd/mm/yyyy

Viewed 36

I am facing a date format converting issue now. There will be some date format data passing in like: Jul 2022 or some times 11/2022 or Sept 2022 or sometimes 11/11/2021. I can't control what date format will be passing in. But I have to return exactly date if dd/mm/yyyy is passing in. For all other format that missing date like mm/yyyy, I have to return end of month date format like: if Sept 2022 passes in, I will return 09/30/2022.

Currently, my code will be like this. parse will return a date not that randomly. But it will add today's date to it like below. Is there a way to achieve my goal easily? from dateutil.parser import parse parse(columns[2])

parser.parse("09/2022").date() datetime.date(2022, 9, 23)

1 Answers

dateutil's parser accepts a "default" kwarg, which allows you to set a default date in case you supply an incomplete date string. However, since here the default date varies depending on the input, you'll need another step, to calculate the end-of-month date to use as default. Ex:

from datetime import datetime
from dateutil import parser
from dateutil.relativedelta import relativedelta

examples = ["Jul 2022", "11/2022", "Sept 2022", "11/11/2021"]
expected = [datetime(2022,7,31), datetime(2022,11,30), datetime(2022,9,30), datetime(2021,11,11)]

for have, want in zip(examples, expected):
    # step one: parse.
    dt = parser.parse(have)
    # step two: calculate end of month
    dt_eom = dt + relativedelta(day=31)
    # step three: parse again with eom as default date:
    dt_out = parser.parse(have, default=dt_eom)
    
    print(have, dt_out, dt_out==want)
    
# Jul 2022 2022-07-31 00:00:00 True
# 11/2022 2022-11-30 00:00:00 True
# Sept 2022 2022-09-30 00:00:00 True
# 11/11/2021 2021-11-11 00:00:00 True
Related