在 Python 中,如何将“datetime”对象转换为秒?
- 2025-01-20 09:07:00
- admin 原创
- 78
问题描述:
我有一堆日期时间对象,我想计算每个对象自过去某个固定时间以来的秒数(例如自 1970 年 1 月 1 日以来)。
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
这似乎只是区分不同天数的日期:
t.toordinal()
如何将对象转换datetime
为秒?
解决方案 1:
对于 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.utc
是否使用 Python 3。
解决方案 2:
从 Python 3.3 开始,使用该datetime.timestamp()
方法变得非常简单。当然,这只有在您需要 1970-01-01 UTC 的秒数时才有用。
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
返回值将是一个浮点数,表示秒的偶数部分。如果日期时间不考虑时区(如上例所示),则将假定日期时间对象表示本地时间,即它将是从您所在位置的当前时间到 1970-01-01 UTC 的秒数。
解决方案 3:
获取 Unix 时间(自 1970 年 1 月 1 日以来的秒数):
>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0
解决方案 4:
可能偏离主题:从日期时间获取 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 偏移量。在此示例中,偏移量为 +1h,即 UTC+0100。
参考:
日期时间.日期.时间元组
时间.mktime
日期时间.日期时间.来自时间戳
时间模块中的介绍解释了 POSIX 时间、1970 年纪元、UTC、TZ、DST...
解决方案 5:
int (t.strftime("%s"))
也有效
解决方案 6:
来自python文档:
timedelta.total_seconds()
返回持续时间包含的总秒数。相当于
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
使用真除法进行计算。
请注意,对于非常大的时间间隔(大多数平台上大于 270 年),此方法将失去微秒的精度。
此功能是 2.7 版中的新功能。
解决方案 7:
尽管我猜这是默认的需求,但我并没有在所有的答案中看到这一点:
t_start = datetime.now()
sleep(2)
t_end = datetime.now()
duration = t_end - t_start
print(round(duration.total_seconds()))
如果不使用.total_seconds()
,它会抛出:TypeError: type datetime.timedelta doesn't define __round__ method
。
例子:
>>> duration
datetime.timedelta(seconds=53, microseconds=621861)
>>> round(duration.total_seconds())
54
>>> duration.seconds
53
拍摄duration.seconds
仅需几秒,抛开微秒,就像您跑步一样math.floor(duration.total_seconds())
。
解决方案 8:
为了准确起见,比较 4 种最常见的方法:
方法一:手动计算
from datetime import datetime
total1 = int(datetimeobj.strftime('%S'))
total1 += int(datetimeobj.strftime('%M')) * 60
total1 += int(datetimeobj.strftime('%H')) * 60 * 60
total1 += (int(datetimeobj.strftime('%j')) - 1) * 60 * 60 * 24
total1 += (int(datetimeobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
print ("Method #1: Manual")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total1)
print ("After: %s" % datetime.fromtimestamp(total1))
输出:
Method #1: Manual
Before: 1970-10-01 12:00:00
Seconds: 23630400
After: 1970-10-01 16:00:00
准确度测试:失败(时区偏移)
方法二:时间模块
import time
from datetime import datetime
total2 = int(time.mktime(datetimeobj.timetuple()))
print ("Method #2: Time Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total2)
print ("After: %s" % datetime.fromtimestamp(total2))
输出:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
准确度测试:通过
方法三:日历模块
import calendar
from datetime import datetime
total3 = calendar.timegm(datetimeobj.timetuple())
print ("Method #3: Calendar Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total3)
print ("After: %s" % datetime.fromtimestamp(total3))
输出:
Method #3: Calendar Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 16:00:00
准确度测试:失败(时区偏移)
方法 4:日期时间时间戳
from datetime import datetime
total4 = datetimeobj.timestamp()
print ("Method #4: datetime timestamp")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total4)
print ("After: %s" % datetime.fromtimestamp(total4))
输出:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
准确度测试:通过
结论
所有 4 种方法都将日期时间转换为纪元(总秒数)
手动方法和日历模块方法均能感知时区。
datetime.timestamp() 和 time.mktime() 方法均不了解时区。
最简单的方法:datetime.timestamp()
解决方案 9:
要将表示 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.3
如果您需要Python 版本的解决方案,请点击链接。
解决方案 10:
我尝试了标准库的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
解决方案 11:
Python 提供了对日期时间的操作来计算两个日期之间的差异。在你的情况下,这将是:
t - datetime.datetime(1970,1,1)
返回的值是一个 timedelta 对象,您可以使用成员函数total_seconds从中获取以秒为单位的值。
(t - datetime.datetime(1970,1,1)).total_seconds()
解决方案 12:
import datetime
import math
def getSeconds(inputDate):
time = datetime.date.today().strftime('%m/%d/%Y')
date_time = datetime.datetime.strptime(time, '%m/%d/%Y')
msg = inputDate
props = msg.split(".")
a_timedelta = datetime.timedelta
if(len(props)==3):
a_timedelta = date_time - datetime.datetime(int(props[0]),int(props[1]),int(props[2]))
else:
print("Invalid date format")
return
seconds = math.trunc(a_timedelta.total_seconds())
print(seconds)
return seconds
示例 getSeconds("2022.1.1")
解决方案 13:
在 python 3.x 中查找代码块处理时间(以毫秒为单位)的标准方法如下:
import datetime
t_start = datetime.datetime.now()
# Here is the python3 code, you want
# to check the processing time of
t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")