Python trouble converting milliseconds to datetime and back -
so have 2 functions converting python datetime.datetime() objects , milliseconds. cannot figure out going wrong. here's i'm working with:
>>> import datetime >>> def mil_to_date(mil): """date items rest services reported in milliseconds, function convert milliseconds 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 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 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 lose 5 hours?? for reason, losing 5 hours. overlooking obvious? or there problem 1 or both of functions?
the reason date_to_mil works utc , mil_to_date doesn't. should replace utcfromtimestamp fromtimestamp.
further explanation:
in code, epoch date of epoch in utc (but object without time-zone). date local since fromtimestamp returns local time:
if optional argument tz none or not specified, timestamp converted platform’s local date , time, , returned datetime object naive
so subtract utc epoch local datetime , delay local delay utc.
Comments
Post a Comment