Skip to content

Latest commit

 

History

History
20 lines (14 loc) · 688 Bytes

20230113130529.md

File metadata and controls

20 lines (14 loc) · 688 Bytes

make a datetime timezone aware

I just ran into this error using python-dateutil: "can't compare offset-naive and offset-aware datetimes".

I hit this because datetime.now() does no make a "timezone aware" datetime.

But this is easy to fix with this one liner (source: https://stackoverflow.com/a/41624199).

I chose this way because it's Standard Library only, no external dependencies (pytz):

>>> from datetime import datetime, timezone
>>> now = datetime.now()
>>> now  # "naive"
datetime.datetime(2023, 1, 13, 13, 12, 43, 868109)
>>> now.replace(tzinfo=timezone.utc)  # "aware"
datetime.datetime(2023, 1, 13, 13, 12, 43, 868109, tzinfo=datetime.timezone.utc)

#datetime