[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.python

converting a timezone-less datetime to seconds since the epoch

Chris Withers

3/16/2010 1:47:00 PM

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())

class Test(TestCase):

def check(self,*args):
epoch = datetime.utcfromtimestamp(0)
dt = datetime(*args)
actual = timestamp(dt)
d = dt - epoch
expected = d.seconds + 60*60*24*d.days
self.assertEquals(expected,actual,
'%s != %s (diff %s)'%(expected,actual,expected-actual))

def test_xmas(self):
self.check(2009, 12, 25, 1, 2, 3, 456789)

def test_midsummer(self):
self.check(2009, 6, 21, 2, 3, 4, 5678)

For me, test_midsummer fails. I'd be interested in knowing wheher both
tests pass for other people.

I'd be *more* interested in knowing either why the timestamp function or
the tests are wrong and how to correct them...

cheers,

Chris