converting a timezone-less datetime to seconds since the epoch

C

Chris Withers

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top