0

My code of pytz astimezone as below adds extra 56 minutes when converting New York time to London time, when it is not for year 1900.

The other similar questions seem to be converting to or from a time zone to the default machine time zone. What I fail here is converting from a specific time zone to another specific time zone

Can someone help to point out what went wrong? Thanks a lot

import datetime
import pytz
import sys
print(sys.version)
NYTime = datetime.datetime(2023,3,28,6,0,0,tzinfo=pytz.timezone('America/New_York'))
print("NYTime is " + NYTime.strftime("%Y%m%d-%H:%M:%S"))
LondonTime = NYTime.astimezone(pytz.timezone('Europe/London'))
print("LondonTime is " + LondonTime.strftime("%Y%m%d-%H:%M:%S"))

returns

3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
NYTime is 20230328-06:00:00
LondonTime is 20230328-11:56:00

and the below

import datetime
import pytz
import sys
print(sys.version)
NYTime = datetime.datetime(2023,3,28,6,0,0,tzinfo=pytz.timezone('America/New_York'))
print("NYTime is " + NYTime.strftime("%Y%m%d-%H:%M:%S"))
LondonTime = pytz.timezone('Europe/London').localize(NYTime)
print("LondonTime is " + LondonTime.strftime("%Y%m%d-%H:%M:%S"))

returns

ValueError: Not naive datetime (tzinfo is already set)

Henry
  • 57
  • 6
  • 1
    See: https://stackoverflow.com/questions/6410971/python-datetime-object-show-wrong-timezone-offset/6411149. In your code, the fix is to use `astimezone` or `localize` when creating `NYTime`. – slothrop Mar 28 '23 at 16:15
  • I tried `LondonTime = pytz.timezone('Europe/London').localize(NYTime)` instead, and it returns with error of `ValueError: Not naive datetime (tzinfo is already set)` – Henry Mar 28 '23 at 18:30
  • The other similar questions seem to be converting to or from a time zone to the default machine time zone. What I fail here is converting from a specific time zone to another specific time zone – Henry Mar 28 '23 at 18:40
  • `localize` is used to make naive datetime objects aware, i.e. attach a time zone to a datetime that had none previously. In your code example, `NYTime` isn't created correctly, it has to be `pytz.timezone('America/New_York').localize(datetime.datetime(2023,3,28,6,0,0))`, Then you could convert it to another tz for example. – FObersteiner Mar 28 '23 at 19:02
  • Thanks a lot. I think that works, and that may also answer the below most similar question for "the other way around" in "This suggests that you should be converting from UTC to America/New_York, not the other way around, using astimezone" https://stackoverflow.com/questions/74018430/why-is-pytz-wrong-by-56-minutes – Henry Mar 28 '23 at 19:09
  • @Henry I think the answer to the question you linked in the comment above is misleading. I've left a comment there to clarify that. Bottom line: if you have to work with pytz, always `localize` to set the timezone, or even UTC. That seems most error-proof to me. – FObersteiner Mar 29 '23 at 06:55

0 Answers0