1

I am trying to convert a timezone aware datetime.datetime object to UTC and make it naive. For the conversion, I use the following code:

from datetime import datetime
import pytz

dt: datetime = datetime(2023, 1, 2, 12, 0, 0, tzinfo=pytz.timezone("Europe/Amsterdam"))
print(pytz.timezone("Europe/Amsterdam").utcoffset(dt=datetime.now()))
print(dt)
print(dt.astimezone(pytz.timezone("UTC")))

This outputs the following:

1:00:00
2023-01-02 12:00:00+00:18
2023-01-02 11:42:00+00:00

For some reason, the time offset ends up being only 18 minutes instead on one hour. If I try to accomplish the opposite (from UTC to Europe/Amsterdam) it does work correctly:

from datetime import datetime
import pytz

dt: datetime = datetime(2023, 1, 2, 12, 0, 0, tzinfo=pytz.timezone("UTC"))
print(dt)
print(dt.astimezone(pytz.timezone("Europe/Amsterdam")))

Output (just as expected):

1:00:00
2023-01-02 12:00:00+00:00
2023-01-02 13:00:00+01:00

Could anybody tell me why this is happening and how I could fix it? Or is there even a simpler method to convert to UTC and make the datetime naive?

Axel Köhler
  • 911
  • 1
  • 8
  • 34

1 Answers1

1

See pytz documentation:

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

Instead you should use localize() function. This will work fine:

pytz.timezone("Europe/Amsterdam").localize(datetime(2023, 1, 2, 12, 0, 0))

Update: as mentioned in the comment, pytz is deprecated, use zoneinfo. Example.

Alex Bochkarev
  • 2,851
  • 1
  • 18
  • 32
  • 3
    `pytz` is deprecated; the standard library has `zoneinfo` since Python 3.9. [Example](https://stackoverflow.com/a/63628816/10197418). – FObersteiner Jan 02 '23 at 19:44