在 Python 中将 datetime.date 转换为 UTC 时间戳 [英] Converting datetime.date to UTC timestamp in Python

查看:66
本文介绍了在 Python 中将 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)

首先将日期对象转换为日期时间也无济于事.我在这个 link 中尝试了示例,但是:

from pytz import utc, timezone从日期时间导入日期时间从时间导入 mktimeinput_date = 日期时间(年=2011,月=1,日=15)

现在:

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

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

确实有效.

那么普遍的问题:如何根据 UTC 将日期转换为自纪元以来的秒数?

解决方案

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

<预><代码>>>>从日期时间导入日期时间,日期>>>导入日历>>>timestamp1 = calendar.timegm(d.timetuple())>>>datetime.utcfromtimestamp(timestamp1)datetime.datetime(2011, 1, 1, 0, 0)

如果 d 在本地时区:

<预><代码>>>>导入时间>>>timestamp2 = time.mktime(d.timetuple()) # 不要将它与 UTC 日期一起使用>>>datetime.fromtimestamp(timestamp2)datetime.datetime(2011, 1, 1, 0, 0)

timestamp1timestamp2 如果本地时区的午夜与 UTC 的午夜不是同一时间实例,则可能不同.

如果 d 对应于 不明确的当地时间(例如,在 DST 过渡期间) 或者如果 d 是过去(未来)日期,UTC 偏移可能已经不同了并且 C mktime() 无法访问 指定平台上的 tz 数据库.您可以使用pytz 模块(例如,通过tzlocal.get_localzone())来在所有平台上访问 tz 数据库.另外,utcfromtimestamp() 可能会失败,并且 mktime() 如果使用 "right" 时区,则可能会返回非 POSIX 时间戳.

<小时>

在没有calendar.timegm()的情况下转换表示UTC日期的datetime.date对象:

DAY = 24*60*60 # POSIX 天(以秒为单位)(精确值)时间戳 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY时间戳 = (utc_date - date(1970, 1, 1)).days * DAY

如何根据 UTC 将日期转换为自纪元以来的秒数?

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

Python 3.3+

datetime.timestamp():

from datetime 导入时区时间戳 = dt.replace(tzinfo=timezone.utc).timestamp()

注意:必须明确提供 timezone.utc 否则 .timestamp() 假设您的原始日期时间对象位于本地时区.

Python 3 (<3.3)

来自 datetime.utcfromtimestamp():

<块引用>

没有方法可以从日期时间实例中获取时间戳,但是对应于日期时间实例 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)

有趣的阅读:纪元时间与一天中的时间的区别几点了?过去了多少秒?

另见:datetime 需要一个epoch"方法

Python 2

为 Python 2 调整上述代码:

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

where timedelta.total_seconds() 等价于 (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6)/10**6 在启用真除法的情况下计算.>

示例

from __future__ 导入师从日期时间导入日期时间,时间增量def totimestamp(dt, epoch=datetime(1970,1,1)):td = dt - 纪元# 返回 td.total_seconds()返回 (td.microseconds + (td.seconds + td.days * 86400) * 10**6)/10**6现在 = datetime.utcnow()现在打印打印时间戳(现在)

注意浮点问题.

输出

2012-01-08 15:34:10.0224031326036850.02

如何将可感知的 datetime 对象转换为 POSIX 时间戳

assert dt.tzinfo 不是 None 并且 dt.utcoffset() 不是 None时间戳 = dt.timestamp() # Python 3.3+

在 Python 3 上:

from datetime import datetime, timedelta, timezone纪元 = 日期时间(1970, 1, 1, tzinfo=timezone.utc)时间戳 = (dt - epoch)/timedelta(seconds=1)integer_timestamp = (dt - epoch)//timedelta(seconds=1)

在 Python 2 上:

# utc 时间 = 本地时间 - utc 偏移量utc_naive = dt.replace(tzinfo=None) - dt.utcoffset()时间戳 = (utc_naive - datetime(1970, 1, 1)).total_seconds()

I am dealing with dates in Python and I need to convert them to UTC timestamps to be used inside Javascript. The following code does not work:

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

Converting the date object first to datetime also does not help. I tried the example at this link from, but:

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

and now either:

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

or

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

does work.

So general question: how can I get a date converted to seconds since epoch according to UTC?

解决方案

If d = date(2011, 1, 1) is in UTC:

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

If d is in local timezone:

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

timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC.

mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used.


To convert datetime.date object that represents date in UTC without 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

How can I get a date converted to seconds since epoch according to UTC?

To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float).

Python 3.3+

datetime.timestamp():

from datetime import timezone

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

Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone.

Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt:

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

And for an aware dt:

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

Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed?

See also: datetime needs an "epoch" method

Python 2

To adapt the above code for Python 2:

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

where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled.

Example

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)

Beware of floating-point issues.

Output

2012-01-08 15:34:10.022403
1326036850.02

How to convert an aware datetime object to POSIX timestamp

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

On 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)

On 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()

这篇关于在 Python 中将 datetime.date 转换为 UTC 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆