簡體   English   中英

在python中優化datetime.date到unix時間戳轉換

[英]Optimizing datetime.date to unix timestamp conversion in python

我一直在努力盡可能快地做到這一點,同時也避免了時區問題。

這種方法似乎是最慢的:

def to_unix_timestamp(stamp):
    return int(stamp.strftime('%s'))

它產生以下結果:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
4328301    1.620    0.000   10.009    0.000 utils.py:13(to_unix_timestamp)

這似乎好一點,但仍然相對較慢:

def to_unix_timestamp(stamp):
    return time.mktime(stamp.timetuple())

結果:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
4328301    1.381    0.000    8.158    0.000 utils.py:13(to_unix_timestamp)

有什么方法可以在不搞砸時區的情況下實現重大加速? 請注意,我僅限於 python 2.7。

定義d0 = datetime.date(1970, 1, 1) ,然后執行(stamp - d0).total_seconds() ? … – 傑森哈珀

我遇到了我擔心的“時區”問題。 在針對其他方法進行驗證后,我發現來自此方法的時間向前偏移了一個小時。 知道是什么原因造成的嗎?

是的,其他方法隱含地使用本地時間,考慮到您的時區。 datetime.date對象d0 (具有 1 天分辨率)不攜帶該時區信息,因此在采用差異stamp - d0時存在差異。 為了糾正這個問題,我們可以構建一個代表真實紀元的d0

d0 = datetime.datetime.fromtimestamp(0)

這樣, (datetime.datetime.combine(stamp, datetime.time.min) - d0).total_seconds()產生您期望的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM