问题:在Python中,如何将“ datetime”对象转换为秒?

为这个简单的问题表示歉意…我是Python的新手…我四处搜寻,似乎没有任何反应。

我有一堆datetime对象,我想计算每个对象过去某个固定时间以来的秒数(例如,自1970年1月1日起)。

import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)

这似乎只能区分具有不同日期的日期:

t.toordinal()

任何帮助深表感谢。

Apologies for the simple question… I’m new to Python… I have searched around and nothing seems to be working.

I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).

import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)

This seems to be only differentiating between dates that have different days:

t.toordinal()

Any help is much appreciated.


回答 0

在1970年1月1日这个特殊日期,有多种选择。

对于任何其他开始日期,您需要以秒为单位获取两个日期之间的差额。将两个日期相减得到一个timedelta对象,从Python 2.7开始,该对象具有total_seconds()功能。

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

通常以UTC指定开始日期,因此,要获得正确的结果,datetime您也应使用UTC输入该公式。如果您datetime尚未使用UTC,则需要先进行转换,再使用它,或附加tzinfo具有适当偏移量的类。

如评论中所述,如果您有tzinfo附件,datetime则在开始日期也需要一个附件,否则减法将会失败;对于上面的示例,tzinfo=pytz.utc如果使用Python 2或tzinfo=timezone.utcPython 3 ,我会添加。

For the special date of January 1, 1970 there are multiple options.

For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn’t in UTC already, you’ll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you’ll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.


回答 1

要获取Unix时间(自1970年1月1日以来的秒数):

>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0

To get the Unix time (seconds since January 1, 1970):

>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0

回答 2

从Python 3.3开始,使用此datetime.timestamp()方法变得非常容易。当然,这仅在需要从1970-01-01 UTC开始的秒数时才有用。

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

返回值将是代表偶数秒的浮点数。如果datetime是时区朴素的(如上例所示),则将假定datetime对象代表本地时间,即,它是从您所在位置的当前时间到1970-01-01 UTC的秒数。

Starting from Python 3.3 this becomes super easy with the datetime.timestamp() method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.


回答 3

也许离题:从日期时间获取UNIX / POSIX时间并将其转换回:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

请注意,不同的时区会影响结果,例如我当前的TZ / DST返回:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

因此,应该考虑使用功能的UTC版本将其标准化为UTC。

请注意,先前的结果可用于计算您当前时区的UTC偏移量。在此示例中,这是+1小时,即UTC + 0100。

参考文献:

Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:

>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0

# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)

Note that different timezones have impact on results, e.g. my current TZ/DST returns:

>>>  time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h

therefore one should consider normalizing to UTC by using UTC versions of the functions.

Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.

References:


回答 4

int (t.strftime("%s")) 也可以

int (t.strftime("%s")) also works


回答 5

从python文档:

timedelta.total_seconds()

返回持续时间中包含的总秒数。相当于

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

在启用真除法的情况下进行计算。

请注意,对于非常长的时间间隔(在大多数平台上大于270年),此方法将失去微秒的精度。

此功能是2.7版中的新增功能。

from the python docs:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

computed with true division enabled.

Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.

This functionality is new in version 2.7.


回答 6

要将代表UTC时间的datetime对象转换为POSIX时间戳

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

要将代表本地时区中时间的datetime对象转换为POSIX时间戳,请执行以下操作:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

请参阅如何在Python中将本地时间转换为UTC?如果tz数据库在给定平台上可用;仅有stdlib的解决方案可能有效

如果您需要<3.3Python版本的解决方案,请点击链接。

To convert a datetime object that represents time in UTC to POSIX timestamp:

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

To convert a datetime object that represents time in the local timezone to POSIX timestamp:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.

Follow the links if you need solutions for <3.3 Python versions.


回答 7

我尝试了标准库的calendar.timegm,它工作得很好:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

参考:https : //docs.python.org/2/library/calendar.html#calendar.timegm

I tried the standard library’s calendar.timegm and it works quite well:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。