加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python将毫秒转换为datetime并返回

发布时间:2020-12-20 11:42:33 所属栏目:Python 来源:网络整理
导读:所以我有两个函数用于将 python datetime.datetime()对象转换为毫秒数.我无法弄清楚这出错的地方.这是我正在使用的: import datetime def mil_to_date(mil): """date items from REST services are reported in milliseconds,this function will convert mi
所以我有两个函数用于将 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,4,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读