converting a timezone-less datetime to seconds since the epoch

Chris Withers chris at simplistix.co.uk
Wed Apr 7 10:57:10 CEST 2010


Hi Chris,

Chris Rebert wrote:
> from calendar import timegm
> 
> def timestamp(dttm):
>     return timegm(dttm.utctimetuple())
> #the *utc*timetuple change is just for extra consistency
> #it shouldn't actually make a difference here
> 
> And problem solved. As for what the problem was:
> 
> Paraphrasing the table I got added to the time module docs:
> (http://docs.python.org/library/time.html)

That table is not obvious :-/
Could likely do with its own section...

> To convert from struct_time in ***UTC***
> to seconds since the epoch
> use calendar.timegm()

...and really, wtf is timegm doing in calendar rather than in time? ;-)

>> I'd be *more* interested in knowing either why the timestamp function or the
>> tests are wrong and how to correct them...
> 
> You used a function intended for local times on UTC time data, and
> therefore got incorrect results.

Thanks for the info, I don't think I'd ever have gotten to the bottom of 
this on my own! :-)

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
             - http://www.simplistix.co.uk



More information about the Python-list mailing list