Gabriel Magno
Gabriel Magno

Reputation: 405

Python: time.mktime returning the same value for different dates

I was working on some python scripts to calculate the time spent since an older date, and surprisingly got a negative result. I realized that the problem may be in the time.mktime function. Let's get this code:

import time
import datetime

before = datetime.datetime(2010, 10, 17, 0, 0, 0)
after = datetime.datetime(2010, 10, 17, 1, 0, 0)

print "%s = %f" % (before, time.mktime(before.timetuple()))
print "%s = %f" % (after, time.mktime(after.timetuple()))

On my Linux 32-bit Python 2.6.4, the output is:

2010-10-17 00:00:00 = 1287284400.000000
2010-10-17 01:00:00 = 1287284400.000000

The same timestamp for different times! Am I doing something wrong?

Upvotes: 0

Views: 3311

Answers (2)

João Neves
João Neves

Reputation: 957

Note that mktime gives you the representation of your local time, with Daylight Savings if applicable to your system locale. This can lead to some odd behaviors.

You may prefer calendar.timegm which gives you UTC time.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

No. DST in Brazil started on October 17, 2010, so one hour is missing.

Upvotes: 6

Related Questions