Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - calendar.timegm() vs. time.mktime()

I seem to have a hard time getting my head around this.

What's the difference between calendar.timegm() and time.mktime()?

Say I have a datetime.datetime with no tzinfo attached, shouldn't the two give the same output? Don't they both give the number of seconds between epoch and the date passed as a parameter? And since the date passed has no tzinfo, isn't that number of seconds the same?

>>> import calendar
>>> import time
>>> import datetime
>>> d = datetime.datetime(2010, 10, 10)
>>> calendar.timegm(d.timetuple())
1286668800
>>> time.mktime(d.timetuple())
1286640000.0
>>> 
like image 768
ibz Avatar asked Jun 02 '10 10:06

ibz


2 Answers

time.mktime() assumes that the passed tuple is in local time, calendar.timegm() assumes it's in GMT/UTC. Depending on the interpretation the tuple represents a different time, so the functions return different values (seconds since the epoch are UTC based).

The difference between the values should be equal to the time zone offset of your local time zone.

like image 152
sth Avatar answered Oct 08 '22 03:10

sth


calendar.timegm converts from UTC timestamp, time.mktime converts from local time not UTC.

8 hours difference in their results corresponds exactly to timezone of your location.

like image 28
SilentGhost Avatar answered Oct 08 '22 01:10

SilentGhost