search

Home  >  Q&A  >  body text

python中datetime类型的utc时间如何转成时间戳?

import datetime

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

PHPzPHPz2890 days ago607

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-18 09:05:02

    import calendar
    calendar.timegm(utc_timetuple)

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:05:02

    Actually, the questioner here misunderstood the meaning of mktime. Let’s take a look at the official documentation of 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 What is passed should be the local time, not the utc time, so if you want to get the timestamp of the specified utc time, the simpler method is:

    1. Directly subtract the Unix timestamp start time, that is

    timestamp = (now - datetime(1970, 1, 1)).total_seconds()
    1. Convert to local time

    now = datetime.datetime.now()
    timestamp = time.mktime(now.timetuple())

    Of course, there are many methods. Here are just two methods that are easier to understand. If you want to know more, here is a link for your reference: Converting datetime.date to UTC timestamp in Python

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:05:02

    @yylucifer Well said. The main problem is timezone conversion.
    For your problem, you can use the following method

    # 基本上相等,但是会由于计算的耗时导致无法完全相等
    # 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 

    reply
    0
  • Cancelreply