Python无法将毫秒转换为日期时间并返回

时间:2015-04-24 17:02:52

标签: python python-2.7 datetime

所以我有两个函数用于将python datetime.datetime()对象转换为毫秒数。我无法弄清楚这出错的地方。以下是我正在使用的内容:

>>> 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??

由于某种原因,我失去了5个小时。我忽略了一些明显的东西吗或者我的一个或两个功能有问题吗?

2 个答案:

答案 0 :(得分:4)

原因是date_to_mil适用于UTCmil_to_date则不适用。您应该将utcfromtimestamp替换为fromtimestamp

进一步解释:

在您的代码中,epoch是UTC中纪元的日期(但该对象没有任何时区)。但date是本地的,因为fromtimestamp返回当地时间:

  

如果可选参数tz为None或未指定,则时间戳为   转换为平台的本地日期和时间,并返回   datetime对象是天真的

因此,您从本地日期时间中减去UTC时期,并得到延迟,这是您当地的UTC延迟。

答案 1 :(得分:3)

如果input is UTC then to get POSIX timestamp为整数毫秒:

from datetime import datetime, timedelta

def timestamp_millis(utc_time, epoch=datetime(1970, 1, 1)):
    """Return milliseconds since Epoch as integer."""
    td = utc_time - epoch
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) // 10**3

注意:公式可能会产生不同的结果:int(td.total_seconds() * 1000)

反之:从POSIX时间获得UTC时间,以毫秒为单位:

def datetime_from_millis(millis, epoch=datetime(1970, 1, 1)):
    """Return UTC time that corresponds to milliseconds since Epoch."""
    return epoch + timedelta(milliseconds=millis)

它支持正面和负面millis

注意:None处理发生在这些函数之外。

示例:

>>> datetime_from_millis(1394462888000)
datetime.datetime(2014, 3, 10, 14, 48, 8)
>>> datetime.utcfromtimestamp(1394462888)
datetime.datetime(2014, 3, 10, 14, 48, 8)
>>> timestamp_millis(_)
1394462888000

结果与你问题中的结果不同!

gmtime(0).year != 1970TZ=right/UTC个案会被忽略。