Home > Net >  Why is python's datetime conversion wrong in one direction?
Why is python's datetime conversion wrong in one direction?

Time:01-03

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?

CodePudding user response:

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))
  • Related