python中datetime类型的utc时间如何转成时间戳?
PHPz
PHPz 2017-04-18 09:03:02
0
3
595

import datetime

now = datetime.datetime.utcnow()
这个now如何转成时间戳。。
用time.mktime(now.timetuple())这个方法产生的时间戳比time.time()产生的时间戳少28800秒,
现在我的方法是手动加上28800秒产生时间戳,,有没有更好的方法

PHPz
PHPz

学习是最好的投资!

全部回复(3)
黄舟

雷雷

Ty80

其实这里题主理解错了 mktime 的意思,我们来看一下 python 的官方文档:mktime 的意思,我们来看一下 python 的官方文档:

time.mktime(t)
This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

mktime

time.mktime(t)
This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.
  1. mktime 传递的应该是本地的时间,而不是 utc 时间,所以,如果你想获得指定 utc 时间的时间戳,简单点的方法有:

  2. 直接减 Unix 的时间戳开始时间,也就是
    1. timestamp = (now - datetime(1970, 1, 1)).total_seconds()
    转换成本地时间

    🎜
    now = datetime.datetime.now()
    timestamp = time.mktime(now.timetuple())
    🎜当然,方法是有很多的,这里只是列举两种比较容易理解的方法。如果想知道更多的内容,这里有个链接可以供题主参考:Converting datetime.date to UTC timestamp in Python🎜
    伊谢尔伦

    @yylucifer 说的很好。 主要时timezone的转换问题。
    对于你的问题,可以用下面方法

    # 基本上相等,但是会由于计算的耗时导致无法完全相等
    # time.timezone:The offset of the local (non-DST) timezone, in seconds west of UTC 
    time.mktime(datetime.datetime.utcnow().timetuple()) == time.time() + time.timezone 
    热门教程
    更多>
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板