1

I am trying to understand how datetime objects behave in python

>>> import pytz
>>> from datetime import datetime
>>> now = datetime.now()
>>> now
datetime.datetime(2022, 10, 11, 22, 9, 14, 169110)
>>> now.tzinfo
# even though there is no tzinfo, when converted to utc, it shows 20:09
>>> now.astimezone(pytz.utc)
datetime.datetime(2022, 10, 11, 20, 9, 14, 169110, tzinfo=<UTC>)
>>> pytz.utc.localize(now)
datetime.datetime(2022, 10, 11, 22, 9, 14, 169110, tzinfo=<UTC>)

I am trying to understand the reason of the change in the time with line now.astimezone(pytz.utc) since the datetime object was naive in the first place.

  • In Python, naive datetime represents *local time*. `astimezone` *converts* to UTC, `localize` just specifies that it's UTC (instead of local). That's why you see different results for astimezone and localize here (conversion vs. replacement of timezone info). – FObersteiner Oct 12 '22 at 05:36
  • 1
    If it is a local time, shouldn't it have tzinfo there? What is the use of tzinfo then? – iRestMyCaseYourHonor Oct 12 '22 at 06:45
  • 1
    See the docs, [Aware and Naive Objects](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects). Basically naive doesn't specify anything (tzinfo=None), however I would add that it *behaves* like local time. If you're used to the default being UTC from other languages, then having naive objects represent local time (whatever tz your machine is configured to use) can be confusing. If you want to have it unambiguous, use aware datetime / set tzinfo. – FObersteiner Oct 12 '22 at 07:16
  • 1
    A side note, if you can, use [zoneinfo](https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo) from the standard lib. pytz is deprecated with Python 3.9. WIth zoneinfo, you get rid of one dependency *and* common pytz pitfalls such as [this](https://stackoverflow.com/q/11473721/10197418). – FObersteiner Oct 12 '22 at 07:20

0 Answers0