Skip to content
Advertisement

datetime.combine with timezone is different from datetime.now with timezone

In the below code:

JavaScript

Why are d1 and d2 showing different timezone information?

JavaScript
JavaScript

How do I get the same datetime as datetime.now when using datetime.combine?

Advertisement

Answer

datetime.now effectively converts (localizes) your datetime with the pytz timezone object – from the docs:

If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone.

datetime.combine does not do that. It is as if you would write something like datetime(2020,1,1, tzinfo=pytz.timezone('US/Eastern')) – effectively not adjusting the time zone to the provided date/time. See also e.g. pytz localize vs datetime replace and pytz: The Fastest Footgun in the West for more background info.

The correct way to get d2 with pytz would be

JavaScript

No such issues if using timezone objects from dateutil or zoneinfo (Python 3.9+):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement