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

查看:2180
本文介绍了将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也没有帮助。我尝试了这个链接的示例,但是:

  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).utctupuple())

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

正常工作。



所以一般的问题:根据UTC,如何从日期转换为秒数?

解决方案

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

 > ;>> from datetime import datetime,date 
>>>>进口日历
>>>> timestamp1 = calendar.timegm(d.timetuple())
>>> datetime.utcfromtimestamp(timestamp1)
datetime.datetime(2011,1,1,0,0)

如果 d 在本地时区:

 >> ;>进口时间
>>>> timestamp2 = time.mktime(d.timetuple())#请勿使用UTC DATE
>>> datetime.fromtimestamp(timestamp2)
datetime.datetime(2011,1,1,0,0)

timestamp1 timestamp2 可能会有所不同,如果本地时区的午夜与UTC的午夜不一样的时间



mktime()如果 d 对应于模糊的本地时间(例如,在DST转换期间)或者如果 d 是一个过去(未来)的日期,当utc偏移量可能不同 C mktime()无法访问 tz数据库在给定的平台上。您可以使用 pytz 模块(例如,通过 tzlocal)。 get_localzone())以访问所有平台上的tz数据库。另外, utcfromtimestamp()可能会失败,并且 mktime()可能会返回非POSIX时间戳,如果right时区使用






转换 datetime.date 表示日期的对象,不含 calendar.timegm()

  DAY = 24 * 60 * 60#POSIX天数(精确值)
timestamp =(utc_date.toordinal() - date(1970,1,1).toordinal())* DAY
timestamp =(utc_date - date(1970,1,1))。days * DAY



我可以根据UTC得到一个从时代转换成秒的日期吗?



转换 datetime.datetime (not datetime.date )对象已经表示UTC的时间到相应的POSIX时间戳(a $ code> float )。



Python 3.3 +



datetime.timestamp()

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

注意: timezone.utc 明确地否则 .timestamp()假定您的天真的datetime对象在本地时区。



Python 3(< 3.3)



datetime.utcfromtimestamp()


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




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







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

其中 timedelta.total_seconds() 相当于(td.microseconds +(td.seconds + td



示例



 从__future__进口部门
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 ()
打印现在
打印totimestamp(现在)

当心浮点问题



输出



  2012-01-08 15:34:10.022403 
1326036850.02



如何将意义 datetime 对象转换为POS IX时间戳



  assert dt.tzinfo不为None,dt.utcoffset()不为None 
timestamp = dt。时间戳()#Python 3.3+

在Python 3:

  from datetime import datetime,timedelta,timezone 

epoch = datetime(1970,1,1,tzinfo = timezone.utc)
时间戳=(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()


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

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

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

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