我有一堆datetime对象,我想为每个对象计算从过去的固定时间(例如从1970年1月1日以来)开始的秒数。
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
这似乎只是区分有不同日期的日期:
t.toordinal()
如何将datetime对象转换为秒?
我有一堆datetime对象,我想为每个对象计算从过去的固定时间(例如从1970年1月1日以来)开始的秒数。
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
这似乎只是区分有不同日期的日期:
t.toordinal()
如何将datetime对象转换为秒?
当前回答
将表示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版本的解决方案,请参考链接。
其他回答
来自python文档:
timedelta.total_seconds()
返回持续时间中包含的总秒数。相当于
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
启用真除法时计算。
注意,对于非常大的时间间隔(在大多数平台上超过270年),这种方法将失去微秒精度。
此功能是2.7版中的新功能。
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”)
Int (t.strftime("%s"))也可以
将表示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版本的解决方案,请参考链接。
在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")