Using mktime to convert date to seconds since epoch - omitting elements from the tuple?

Roy Smith roy at panix.com
Wed Jan 2 09:28:04 EST 2013


In article <dfd18cf3-e2c0-4f0e-a4c1-a72924039a15 at googlegroups.com>,
 Victor Hooi <victorhooi at gmail.com> wrote:

> Hi,
> 
> I'm using pysvn to checkout a specific revision based on date - pysvn will 
> only accept a date in terms of seconds since the epoch.
> 
> I'm attempting to use time.mktime() to convert a date (e.g. "2012-02-01) to 
> seconds since epoch.

In what timezone is "2012-02-01" supposed to be interpreted?  You really 
can't do anything without knowing that.

> According to the docs, mktime expects a 9-element tuple.

Over the past couple of years, I have slowly come to embrace the Python 
datetime class.  It makes all of this stuff so much easier.

The one thing it's missing is the ability to parse date strings in a 
sane way (I don't consider strptime() to be sane).  Installing dateutil 
(http://labix.org/python-dateutil) is de rigueur, if for no reason other 
than to get dateutil.parser.parse().  Once you've got that (and assuming 
your 2012-03-01 is in UTC)

>>> epoch = parse("1970-01-01T00:00:00+0000")
>>> t = parse("2012-03-17T00:00:00+0000")
>>> (t - epoch).total_seconds()
1331942400.0

I never want to see another timetuple again.

PS: you need Python 2.7 to get total_seconds().  But, then again, I 
consider Python 2.7 to be de rigueur as well.

PPS: Some additional hints for staying sane while working with dates:

1) Do everything in UTC.

2) Even if you violate rule #1 at the edges, always, without exception, 
store dates in your database (and transmit them over your APIs) in UTC.

3) Run all your servers with their timezones set to UTC.

4) Run NTP everywhere.

5) If in doubt, see rule #2.

6) If it's absolutely impossible to obey rule #2, at least store and 
transmit time in a self-describing format (i.e. one which includes the 
timezone information).

7) If it's absolutely impossible to obey rule #6, run away from the 
project.



More information about the Python-list mailing list