如何将time.struct_time对象转换为datetime对象?
如何把Python中的time.struct_time
对象转换成datetime.datetime
对象呢?
我有一个库是提供time.struct_time
的,另一个库则需要datetime.datetime
。
3 个回答
44
这不是对你问题的直接回答(你的问题已经得到了很好的解答)。不过,我想提醒你,仔细看看你的time.struct_time对象提供了什么,以及其他时间字段可能有什么,这点非常重要。
假设你有一个time.struct_time对象和一些其他的日期/时间字符串,比较这两者,确保你没有丢失数据,也不要无意中创建一个简单的日期时间对象,而是要尽量避免这样。
举个例子,优秀的feedparser模块会返回一个“published”字段,并可能在它的“published_parsed”字段中返回一个time.struct_time对象:
time.struct_time(
tm_year=2013, tm_mon=9, tm_mday=9,
tm_hour=23, tm_min=57, tm_sec=42,
tm_wday=0, tm_yday=252, tm_isdst=0,
)
现在注意一下你从“published”字段实际得到的是什么。
Mon, 09 Sep 2013 19:57:42 -0400
天哪!还有时区信息呢!
在这种情况下,懒人可能会想用优秀的dateutil模块来保留时区信息:
from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()
这样我们就得到了:
published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00
然后你可以使用这个带时区的日期时间对象,把所有时间标准化为UTC,或者转换成你觉得合适的格式。
146
像这样:
import time, datetime
st = time.localtime()
dt = datetime.datetime(*st[:6])
print(dt)
这段代码会输出 2009-11-08 20:32:35
。
更新:如果你想要包含来自 struct_time
值的时区信息,可以使用这个方法:
def datetime_of_struct_time(st: time.struct_time) -> datetime.datetime:
"Convert a struct_time to datetime maintaining timezone information when present"
tz = None
if st.tm_gmtoff is not None:
tz = datetime.timezone(datetime.timedelta(seconds=st.tm_gmtoff))
# datetime doesn't like leap seconds so just truncate to 59 seconds
if st.tm_sec in {60, 61}:
return datetime.datetime(*st[:5], 59, tzinfo=tz)
return datetime.datetime(*st[:6], tzinfo=tz)
这个方法可以和上面的 struct_time
值一起使用:
print(datetime_of_struct_time(st))
输出的结果是 2009-11-08 20:32:35-04:00
。
440
使用 time.mktime() 可以把时间元组(本地时间)转换成自纪元以来的秒数,然后再用 datetime.fromtimestamp() 来获取日期时间对象。
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))