搜尋

首頁  >  問答  >  主體

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

import datetime

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

PHPzPHPz2893 天前617

全部回覆(3)我來回復

  • 黄舟

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

    雷雷

    回覆
    0
  • PHP中文网

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

    其實這裡題主理解錯了 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 產品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 be represented as a valid time, either OverflowError or ValueError will bevalis value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

    mktime 傳遞的應該是本地的時間,而不是 utc 時間,所以,如果你想得到指定 utc 時間的時間戳,簡單點的方法有:

    1. 直接減 Unix 的時間戳開始時間,也就是

    timestamp = (now - datetime(1970, 1, 1)).total_seconds()
    1. 轉換成本地時間

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

    當然,方法是有很多的,這裡只是列舉兩種比較容易理解的方法。如果想知道更多的內容,這裡有個連結可以讓題主參考:Converting datetime.date to UTC timestamp in Python

    回覆
    0
  • 伊谢尔伦

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

    @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 

    回覆
    0
  • 取消回覆