converting a timezone-less datetime to seconds since the epoch
Chris Rebert
clp2 at rebertia.com
Tue Mar 16 10:13:04 EDT 2010
On Tue, Mar 16, 2010 at 6:47 AM, Chris Withers <chris at simplistix.co.uk> wrote:
> Hi All,
>
> We have a bunch of datetime objects that have tzinfo=None.
> We want to turn them into float timestamps in seconds since the epoch.
>
> Here's the first attempt:
>
> import time
> from datetime import datetime
> from unittest import TestCase
>
> def timestamp(dttm):
> return time.mktime(dttm.timetuple())
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)
To convert from struct_time in ***UTC***
to seconds since the epoch
use calendar.timegm()
To convert struct_time in ***local*** time
to seconds since the epoch
use time.mktime()
> 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.
Cheers,
Chris
--
Entering the workforce in 2012
http://blog.rebertia.com
More information about the Python-list
mailing list