pytz and Python timezones

Lawrence D’Oliveiro lawrencedo99 at gmail.com
Sat Jun 11 21:16:38 EDT 2016


On Saturday, June 11, 2016 at 11:37:38 PM UTC+12, Johannes Bauer wrote:
> I try to create a localized timestamp in the easiest possible way.

Localized timestamps are perhaps not as easy as you think.

> So, intuitively, I did this:
> 
> datetime.datetime(2016,1,1,0,0,0,tzinfo=pytz.timezone("Europe/Berlin"))
> 
> Which gives me:
> 
> datetime.datetime(2016, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin'
> LMT+0:53:00 STD>)
> 
> Uuuuuh... what?

A careful reading of <https://docs.python.org/3/library/datetime.html#datetime.datetime> indicates that those classes expect their attributes to already be in local time. I don’t think they have the smarts to examine the tzinfo you pass them and decide which of possibly several sections of historical information might apply to them. So you ended up with it being interpreted according to the oldest section of the “Europe/Berlin” timezone data (the one up to April 1893).

Anyway, that’s my guess.

> This here:
> 
> pytz.timezone("Europe/Berlin").localize(datetime.datetime(2016,1,1))
> 
> Gives me the expected result of:
> 
> datetime.datetime(2016, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin'
> CET+1:00:00 STD>)

Clearly pytz has much more smarts about handling local times.

My general rule about dates/times is: always work in UTC. Convert to local dates/times only for display purposes.



More information about the Python-list mailing list