Search code examples
pythondatetimecalendarepoch

Python's `fromtimestamp` does a discrete jump


I am using datetime.fromtimestamp to convert epoch time into local time. I found that datetime.fromtimestamp does a discrete jump of one hour at a certain point of time and I am completely baffled as to why it does that.

(I am also using time.mktime to convert a datetime object into epoch time, as suggested by Raymond Hettinger. I'm not sure whether this is relevant information for this question, so I'm saying this just in case.)

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time, datetime
>>> def datetime_to_epoch_time(datetime_):
...     return time.mktime(datetime_.timetuple()) + datetime_.microsecond / 1e6
... 

Picking a specific epoch time:

>>> x = datetime_to_epoch_time(datetime.datetime(2012, 3, 30, 3, 0))

Converting it to a datetime using fromtimestamp:

>>> datetime.datetime.fromtimestamp(x)
datetime.datetime(2012, 3, 30, 3, 0)

We get a time of 3am.

Now let's convert the time that's exactly one second before it:

>>> datetime.datetime.fromtimestamp(x-1)
datetime.datetime(2012, 3, 30, 1, 59, 59) 

We suddenly get 1:59am!

What happened? I know that stuff like that happens around leap days, but since when is March 30th a leap day?

I should note that I've had this happen to me only on Linux and not on Windows. And I think that different Linux computers (in different timezones) have a different time point in which fromtimestamp does the jump.


Solution

  • Easy. March 30th is presumably a daylight savings time switch in your timezone.

    So on that day, time did indeed go from 1:59:59 to 3:00:00