将datetime.date转换为UTC时间戳

问题:

我正在处理Python中的日期,我需要将它们转换为UTC时间戳来使用
里面的Javascript。以下代码不起作用:

>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)

将日期对象首先转换为datetime也没有帮助。我尝试了这个link的例子,但是:

from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)

现在或者:

mktime(utc.localize(input_date).utctimetuple())

要么

mktime(timezone('US/Eastern').localize(input_date).utctimetuple())

做工作
所以一般的问题:根据UTC,如何可以将日期转换为秒数?

回答:

如果d = date(2011, 1, 1)为UTC:

>>> from datetime import datetime, date
>>> import calendar
>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011, 1, 1, 0, 0)

如果d在本地时区:

>>> import time
>>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011, 1, 1, 0, 0)

 timestamp1timestamp2可能会有所不同,如果当地时区的午夜与UTC的午夜不一样。
 如果d对应于ambiguous local time (e.g., during DST transition)或如果d是过去(未来)日期,则当mktime()不一致时,mktime()可能会返回错误的结果and C mktime()无法访问the tz database在给定的平台上。你可以use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms。另外utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used
要转换代表日期的datetime.date对象,而不使用calendar.timegm()

DAY = 24*60*60 # POSIX day in seconds (exact value)
timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY
timestamp = (utc_date - date(1970, 1, 1)).days * DAY

根据UTC,如何从日期转换为秒数?

将已经代表UTC时间的datetime.datetime(而不是datetime.date)对象转换为相应的POSIX时间戳(a float)。

Python 3.3+

 datetime.timestamp()

from datetime import timezone

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

注意:有必要明确提供timezone.utc,否则.timestamp()假设您的naive datetime对象在本地时区。

Python 3(<3.3)

datetime.utcfromtimestamp()的文档

没有从datetime实例获取时间戳的方法,但是可以很容易地计算与datetime实例dt对应的POSIX时间戳。对于一个天真的dt:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

而对于一个意识的dt:

timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)

有趣的是:Epoch time vs. time of day关于What time is it?How many seconds have elapsed?之间的差异
参见:datetime needs an “epoch” method

Python 2

为了适应Python 2的上述代码:

timestamp = (dt - datetime(1970, 1, 1)).total_seconds()

其中timedelta.total_seconds()相当于使用真分区计算的(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

示例

from __future__ import division
from datetime import datetime, timedelta

def totimestamp(dt, epoch=datetime(1970,1,1)):
    td = dt - epoch
    # return td.total_seconds()
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 

now = datetime.utcnow()
print now
print totimestamp(now)

当心floating-point issues

产量

2012-01-08 15:34:10.022403
1326036850.02

如何转换意识

assert dt.tzinfo is not None and dt.utcoffset() is not None
timestamp = dt.timestamp() # Python 3.3+

在Python 3:

from datetime import datetime, timedelta, timezone

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)
integer_timestamp = (dt - epoch) // timedelta(seconds=1)

在Python 2:

# utc time = local time              - utc offset
utc_naive  = dt.replace(tzinfo=None) - dt.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: Converting datetime.date to UTC timestamp in Python

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

26 − = 24