[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: converting a timezone-less datetime to seconds since the epoch

Chris Rebert

3/16/2010 2:13:00 PM

On Tue, Mar 16, 2010 at 6:47 AM, Chris Withers <chris@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...)

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.re...