Search code examples
pythondatetimetimezonepytz

Python pytz issue with DST


I am using the command

datetime.datetime.fromtimestamp(int(1364691600)).replace(tzinfo=pytz.utc).astimezone(pytz.timezone("Europe/London"))

This returns

datetime.datetime(2013, 3, 31, 3, 0, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

Surely this should return

datetime.datetime(2013, 3, 31, 2, 0, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)

The reason I think this is because when BST switches it is 1 hour yet here it is doing 2 hours

>>> datetime.datetime.fromtimestamp(int(1364691599)).replace(tzinfo=pytz.utc).astimezone(pytz.timezone("Europe/London"))
datetime.datetime(2013, 3, 31, 0, 59, 59, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

Solution

  • fromtimestamp(tz=None) uses your local timezone and your local timezone is not utc and therefore it is incorrect to call .replace(tzinf=pytz.utc) on the result.

    Pass the timezone directly instead:

    >>>> from datetime import datetime 
    >>> import pytz # $ pip install pytz
    >>> datetime.fromtimestamp(1364691600, pytz.timezone("Europe/London"))
    datetime.datetime(2013, 3, 31, 2, 0, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>)