将datetime。使用Python的UTC时间戳日期。

时间:2021-09-21 02:38:31

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:

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

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

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

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?

那么一般的问题是:根据UTC,我怎么才能让一个日期转换为秒呢?

7 个解决方案

#1


366  

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

如果d =日期(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)

If d is in local timezone:

如果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)

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

timestamp1和timestamp2可能会不同,如果在本地时区的午夜与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.

mktime()可能返回一个错误的结果,如果d对应于一个不明确的本地时间(例如,在DST转换期间),或者如果d是一个过去的(未来)日期,utc偏移可能是不同的,C mktime()没有访问给定平台上的tz数据库。您可以使用pytz模块(例如,通过tzlocal.get_localzone())来访问所有平台上的tz数据库。另外,utcfromtimestamp()可能会失败,而mktime()可能返回非posix时间戳,如果使用“正确”的时区。


To convert datetime.date object that represents date in UTC without calendar.timegm():

将datetime。在UTC中表示日期的对象,没有日历。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).

将datetime。datetime(不是datetime.date)对象,它已经表示UTC中的时间到对应的POSIX时间戳(浮点数)。

Python 3.3+

datetime.timestamp():

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.

注意:必须提供时区。timestamp()假设您的天真的datetime对象位于本地时区。

Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

来自于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:

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

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

And for an aware dt:

对于已知的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

参见:datetime需要一个“epoch”方法。

Python 2

To adapt the above code for Python 2:

为了适应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.

timedelta.total_seconds()相当于(td)。微秒+(td。秒+道明。日期* 24 * 3600)* 10**6)/ 10**6,用真正的除法计算。

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:

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:

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

#2


36  

For unix systems only:

只适用于unix系统:

>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

注1:眩晕观察发现这适用于局部时区。在生产中不使用。

Note 2: Jakub Narębski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

注2:Jakub Narębski指出,这忽略了时区信息甚至offset-aware datetime Python 2.7(测试)。

#3


34  

  • Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).

    假设1:您试图将日期转换为时间戳,但是由于日期包含24小时,因此没有一个时间戳表示该日期。我假设您想要表示该日期的时间戳(00:00 .00)。

  • Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.

    假设2:您当前的日期与某个特定的时区无关,但是您想要确定某个时区(UTC)的偏移量。如果不知道日期所在的时区,就不可能计算特定时区的时间戳。我假设您希望将日期视为本地系统时区。

First, you can convert the date instance into a tuple representing the various time components using the timetuple() member:

首先,您可以使用timetuple()成员将日期实例转换为表示不同时间组件的元组:

dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)

You can then convert that into a timestamp using time.mktime:

然后,您可以使用time.mktime将其转换为时间戳。

ts = time.mktime(dtt) # 1293868800.0

You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:

您可以通过使用epoch时间本身(1970-01-01)来验证该方法,在这种情况下,函数应该返回该日期本地时区的时区偏移量:

d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0

28800.0 is 8 hours, which would be correct for the Pacific time zone (where I'm at).

28800.0是8小时,这对太平洋时区是正确的(我在这里)。

#4


7  

follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()

遵循python2.7文档,您必须使用calendar.timegm()而不是time.mktime()

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

#5


2  

the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:

这个问题有点困惑。时间戳不是UTC -它们是Unix的东西。日期可能是UTC?假设它是,并且如果您使用的是Python 3.2+,简单的日期使这个变得简单:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

if you actually have the year, month and day you don't need to create the date:

如果你真的有一年,一个月和一天你不需要创造日期:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):

如果日期在其他时区(这很重要,因为我们假设没有相关时间的午夜):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:

简单日期的想法是在一个一致的类中收集所有python的日期和时间,这样您就可以进行任何转换。所以,举个例子,它也会反过来:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

]

#6


2  

Using the arrow package:

使用箭头的包:

>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, 
    tm_hour=0, tm_min=0, tm_sec=0, 
    tm_wday=4, tm_yday=365, tm_isdst=0)

#7


0  

A complete time-string contains:

一个完整的时间字符串包含:

  • date
  • 日期
  • time
  • 时间
  • utcoffset [+HHMM or -HHMM]
  • utcoffset[+ HHMM或-HHMM]

For example:

例如:

1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX timestamp:3600

1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX时间戳:3600。

$ python3
>>> from datetime import datetime
>>> from calendar import timegm
>>> tm = '1970-01-01 06:00:00 +0500'
>>> fmt = '%Y-%m-%d %H:%M:%S %z'
>>> timegm(datetime.strptime(tm, fmt).utctimetuple())
3600

Note:

注意:

UNIX timestamp is a floating point number expressed in seconds since the epoch, in UTC.

UNIX时间戳是一个浮点数,它是在UTC中以秒为单位表示的。


Edit:

编辑:

$ python3
>>> from datetime import datetime, timezone, timedelta
>>> from calendar import timegm
>>> dt = datetime(1970, 1, 1, 6, 0)
>>> tz = timezone(timedelta(hours=5))
>>> timegm(dt.replace(tzinfo=tz).utctimetuple())
3600

#1


366  

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

如果d =日期(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)

If d is in local timezone:

如果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)

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

timestamp1和timestamp2可能会不同,如果在本地时区的午夜与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.

mktime()可能返回一个错误的结果,如果d对应于一个不明确的本地时间(例如,在DST转换期间),或者如果d是一个过去的(未来)日期,utc偏移可能是不同的,C mktime()没有访问给定平台上的tz数据库。您可以使用pytz模块(例如,通过tzlocal.get_localzone())来访问所有平台上的tz数据库。另外,utcfromtimestamp()可能会失败,而mktime()可能返回非posix时间戳,如果使用“正确”的时区。


To convert datetime.date object that represents date in UTC without calendar.timegm():

将datetime。在UTC中表示日期的对象,没有日历。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).

将datetime。datetime(不是datetime.date)对象,它已经表示UTC中的时间到对应的POSIX时间戳(浮点数)。

Python 3.3+

datetime.timestamp():

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.

注意:必须提供时区。timestamp()假设您的天真的datetime对象位于本地时区。

Python 3 (< 3.3)

From the docs for datetime.utcfromtimestamp():

来自于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:

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

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

And for an aware dt:

对于已知的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

参见:datetime需要一个“epoch”方法。

Python 2

To adapt the above code for Python 2:

为了适应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.

timedelta.total_seconds()相当于(td)。微秒+(td。秒+道明。日期* 24 * 3600)* 10**6)/ 10**6,用真正的除法计算。

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:

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:

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

#2


36  

For unix systems only:

只适用于unix系统:

>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

注1:眩晕观察发现这适用于局部时区。在生产中不使用。

Note 2: Jakub Narębski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

注2:Jakub Narębski指出,这忽略了时区信息甚至offset-aware datetime Python 2.7(测试)。

#3


34  

  • Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000).

    假设1:您试图将日期转换为时间戳,但是由于日期包含24小时,因此没有一个时间戳表示该日期。我假设您想要表示该日期的时间戳(00:00 .00)。

  • Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.

    假设2:您当前的日期与某个特定的时区无关,但是您想要确定某个时区(UTC)的偏移量。如果不知道日期所在的时区,就不可能计算特定时区的时间戳。我假设您希望将日期视为本地系统时区。

First, you can convert the date instance into a tuple representing the various time components using the timetuple() member:

首先,您可以使用timetuple()成员将日期实例转换为表示不同时间组件的元组:

dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)

You can then convert that into a timestamp using time.mktime:

然后,您可以使用time.mktime将其转换为时间戳。

ts = time.mktime(dtt) # 1293868800.0

You can verify this method by testing it with the epoch time itself (1970-01-01), in which case the function should return the timezone offset for the local time zone on that date:

您可以通过使用epoch时间本身(1970-01-01)来验证该方法,在这种情况下,函数应该返回该日期本地时区的时区偏移量:

d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0

28800.0 is 8 hours, which would be correct for the Pacific time zone (where I'm at).

28800.0是8小时,这对太平洋时区是正确的(我在这里)。

#4


7  

follow the python2.7 document, you have to use calendar.timegm() instead of time.mktime()

遵循python2.7文档,您必须使用calendar.timegm()而不是time.mktime()

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

#5


2  

the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:

这个问题有点困惑。时间戳不是UTC -它们是Unix的东西。日期可能是UTC?假设它是,并且如果您使用的是Python 3.2+,简单的日期使这个变得简单:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

if you actually have the year, month and day you don't need to create the date:

如果你真的有一年,一个月和一天你不需要创造日期:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):

如果日期在其他时区(这很重要,因为我们假设没有相关时间的午夜):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:

简单日期的想法是在一个一致的类中收集所有python的日期和时间,这样您就可以进行任何转换。所以,举个例子,它也会反过来:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

]

#6


2  

Using the arrow package:

使用箭头的包:

>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, 
    tm_hour=0, tm_min=0, tm_sec=0, 
    tm_wday=4, tm_yday=365, tm_isdst=0)

#7


0  

A complete time-string contains:

一个完整的时间字符串包含:

  • date
  • 日期
  • time
  • 时间
  • utcoffset [+HHMM or -HHMM]
  • utcoffset[+ HHMM或-HHMM]

For example:

例如:

1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX timestamp:3600

1970-01-01 06:00:00 +0500 == 1970-01-01 01:00:00 +0000 == UNIX时间戳:3600。

$ python3
>>> from datetime import datetime
>>> from calendar import timegm
>>> tm = '1970-01-01 06:00:00 +0500'
>>> fmt = '%Y-%m-%d %H:%M:%S %z'
>>> timegm(datetime.strptime(tm, fmt).utctimetuple())
3600

Note:

注意:

UNIX timestamp is a floating point number expressed in seconds since the epoch, in UTC.

UNIX时间戳是一个浮点数,它是在UTC中以秒为单位表示的。


Edit:

编辑:

$ python3
>>> from datetime import datetime, timezone, timedelta
>>> from calendar import timegm
>>> dt = datetime(1970, 1, 1, 6, 0)
>>> tz = timezone(timedelta(hours=5))
>>> timegm(dt.replace(tzinfo=tz).utctimetuple())
3600