Search code examples
python-3.xpytz

How can I parse a custom string as a timezone aware datetime?


How can I parse

18 January 2022, 14:50 GMT-5

as a timezone aware datetime.

pytz.timezone('GMT-5')

fails. It appears I may need to parse the GMT part, and manually apply the 5 hours offset post parsing?


Solution

  • Hmm How about maybe:

    import re
    import datetime
    foo = "18 January 2022, 14:50 GMT-5"
    bar = re.sub(r"[+-]\d+$", lambda m: "{:05d}".format(100 * int(m.group())), foo)
    print(datetime.datetime.strptime(bar, "%d %B %Y, %H:%M %Z%z" ))
    

    I think that gives you:

    2022-01-18 14:50:00-05:00