Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python trouble converting milliseconds to datetime and back

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?

like image 472
crmackey Avatar asked Dec 19 '22 04:12

crmackey


1 Answers

The reason for this is that date_to_mil works with UTC and mil_to_date doesn't. You should replace utcfromtimestamp with fromtimestamp.

Further explanation:

In your code, epoch is the date of the epoch in UTC (but the object is without any time-zone). But date is local since fromtimestamp returns a local time:

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive

So you subtract the UTC epoch from the local datetime and you get a delay which is your local delay to UTC.

like image 156
Ella Sharakanski Avatar answered Dec 22 '22 00:12

Ella Sharakanski