Search code examples
python-3.xdatetimepytz

Python convert time zones deviation


I want to use Python to convert times to UTC and compare them. In my experiment, the Tokyo time has a deviation and I do not know if it is a mistake of my approach or a bug?

Code

#!/usr/bin/env python3

import datetime

tz = pytz.timezone("Asia/Tokyo")
date = datetime.datetime.strptime(
    '12:00',
    '%H:%M'
)
date_with_tz = tz.localize(date)
print("Time in Tokyo\t\t: ", date_with_tz.strftime('%H:%M'))

date_as_utc = date_with_tz.astimezone(pytz.utc)
print("Time Tokyo in UTC\t: ", date_as_utc.strftime('%H:%M'))

print("Should 12 (Tokyo) -> 3 (UTC)")

Output

❯ ./time_zone.py
Time in Tokyo           :  12:00
Time Tokyo in UTC       :  02:41

The UTC time should be 3 and not 2:41 ... what is happening here?


Solution

  • You don't need to use localize in this case.

    import datetime, pytz
    
    tokyo = datetime.datetime.now(pytz.timezone("Asia/Tokyo")).replace(hour=12, minute=0, second=0)
    utc = tokyo.astimezone(pytz.utc)
    
    print("Time Tokyo:", tokyo.strftime('%H:%M'))
    print("Time UTC:", utc.strftime('%H:%M'))
    print("Should 12 (Tokyo) -> 3 (UTC)")