我有一堆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对象转换为秒?
当前回答
我试了试标准图书馆的日历。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
其他回答
将表示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版本的解决方案,请参考链接。
我并没有在所有的答案中看到这一点,尽管我猜这是默认的需求:
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没有定义__round__方法。
例子:
>>> duration
datetime.timedelta(seconds=53, microseconds=621861)
>>> round(duration.total_seconds())
54
>>> duration.seconds
53
持续时间。Seconds只使用秒,不考虑微秒,就像运行math.floor(duration.total_seconds())一样。
我试了试标准图书馆的日历。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
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”)
从datetime获取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。
引用:
datetime.date.timetuple time.mktime datetime.datetime.fromtimestamp 时间模块的介绍解释了POSIX时间,1970年纪元,UTC, TZ, DST…