0

I am manually constructing a datetime object in Python:

>>> import datetime
>>> import pytz
>>> dt = datetime.datetime(
...             2020, 4, 3, 12, 0, 0,
...             tzinfo=pytz.timezone('America/Chicago')
...         )
>>> str(dt)
'2020-04-03 12:00:00-05:51'
>>>

On the other hand:

>>> naive = datetime.datetime(2020, 4, 3, 12, 0, 0,)
>>> pytz.timezone('America/Chicago').localize(naive)
datetime.datetime(2020, 4, 3, 12, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>)
>>> dt = pytz.timezone('America/Chicago').localize(naive)
>>> str(dt)
'2020-04-03 12:00:00-05:00'
>>> 

Why is the timezone offset "-05:51" in the first code snippet and "-05:00" in the second. Since Daylight Saving Time is active in America/Chicago on Apr 3, 2020, they should both show "-05:00".

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Have a look at `dateutil`, you could avoid the "localize issue" there. See e.g. [here](https://stackoverflow.com/a/62578255/10197418) for an example ;-) – FObersteiner Jun 26 '20 at 18:32

1 Answers1

1

You can localize a datetime using the following code:

dt = pytz.timezone('America/Chicago').localize(datetime.datetime(2020, 4, 3, 12, 0, 0))
str(dt)

The output is:

'2020-04-03 12:00:00-05:00'
Ferran
  • 46
  • 4