converting a timezone-less datetime to seconds since the epoch

Chris Withers chris at simplistix.co.uk
Tue Mar 16 09:47:12 EDT 2010


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




More information about the Python-list mailing list