Python将毫秒转换为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个小时.我忽略了一些明显的东西吗或者我的一个或两个功能有问题吗?

最佳答案 原因是date_to_mil适用于UTC而mil_to_date不适用.您应该使用fromtimestamp替换utcfromtimestamp.

进一步说明:

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

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

因此,您从本地日期时间中减去UTC时期,并得到一个延迟,即本地延迟到UTC.

点赞