How to compare calendar.timegm() vs. time.mktime() in Python?


If not explicitly stated, the date time functions/modules in Python assume everything in Local time zone.

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.

example

import calendar
import time
from datetime import datetime
dt = datetime(2017, 12, 31)
print(time.mktime(dt.timetuple()))
print(calendar.timegm(dt.timetuple()))

Output

This will give the output −

1514658600.0
1514678400

Updated on: 19-Feb-2020

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements