So I have two functions for converting python datetime.datetime()
objects to and from milliseconds. I cannot figure out where this is going wrong. Here's what I'm working with:
>>> import datetime
>>> def mil_to_date(mil):
"""date items from REST services are reported in milliseconds,
this function will convert milliseconds to datetime objects
Required:
mil -- time in milliseconds
"""
if mil == None:
return None
elif mil < 0:
return datetime.datetime.utcfromtimestamp(0) + datetime.timedelta(seconds=(mil/1000))
else:
return datetime.datetime.fromtimestamp(mil / 1000)
>>> def date_to_mil(date):
"""converts datetime.datetime() object to milliseconds
date -- datetime.datetime() object"""
if isinstance(date, datetime.datetime):
epoch = datetime.datetime.utcfromtimestamp(0)
return long((date - epoch).total_seconds() * 1000.0)
>>> mil = 1394462888000
>>> date = mil_to_date(mil)
>>> date
datetime.datetime(2014, 3, 10, 9, 48, 8) #this is correct
>>> d2m = date_to_mil(date)
>>> d2m
1394444888000L
>>> mil
1394462888000L
>>> date2 = mil_to_date(d2m)
>>> date2
datetime.datetime(2014, 3, 10, 4, 48, 8) #why did I lose 5 hours??
For some reason, I am losing 5 hours. Am I overlooking something obvious? Or is there a problem with one or both of my functions?