Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird .astimezone behavior

Tags:

python

pytz

I am doing some timezone conversions, and I get really weird results. Basically converting between timezones that differ only by whole hours, I still get non-whole results. For example:

from datetime import datetime
from pytz import timezone

datetime(2013, 12, 27, 20, 0, 0, tzinfo=timezone('Europe/Bucharest'))\
    .astimezone(timezone('Europe/Berlin')).replace(tzinfo=None)

gives me

datetime.datetime(2013, 12, 27, 19, 16)

(time difference between Bucharest and Berlin is 1 hour, so I should get 19:00 - instead I get 19:16)

I'm probably missing something really obvious, but I can't figure it out. What am I doing wrong?

like image 798
ibz Avatar asked Dec 27 '13 17:12

ibz


1 Answers

I came across this same issue today, and eventually solved it using the answer @jfs put in the comment of the currently accepted answer. To help anyone else finding this in the future, here is a quick example of what does and doesn't work:

from datetime import datetime
import pytz

naive = datetime.now()
la_tz = pytz.timezone("America/Los_Angeles")

# this doesn't work
with_tz = naive.replace(tzinfo=la_tz)
converted_to_utc = with_tz.astimezone(pytz.utc)
print(converted_to_utc)

# this does work
with_tz = la_tz.localize(naive)
converted_to_utc = with_tz.astimezone(pytz.utc)
print(converted_to_utc)
like image 178
Chris Avatar answered Oct 06 '22 10:10

Chris