【发布时间】:2011-04-14 00:34:58
【问题描述】:
我有一个 python 脚本,我需要比较两个日期。我有一个日期列表作为 time.struct_time 对象,我需要将其与一些 datetime.date 对象进行比较。
如何将 datetime.date 对象转换为 time.struct_time 对象?或者我可以直接使用它们进行比较吗?
【问题讨论】:
我有一个 python 脚本,我需要比较两个日期。我有一个日期列表作为 time.struct_time 对象,我需要将其与一些 datetime.date 对象进行比较。
如何将 datetime.date 对象转换为 time.struct_time 对象?或者我可以直接使用它们进行比较吗?
【问题讨论】:
尝试使用date.timetuple()。来自 Python 文档:
返回一个
time.struct_time比如 由time.localtime()返回。这 小时、分钟和秒为 0,并且 DST 标志为 -1。d.timetuple()是 相当于time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)),其中yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1是 当年的天数 从 1 开始表示 1 月 1 日。
【讨论】:
将日期对象转换为 time.struct_time 对象的示例:
#### Import the necessary modules
>>> dt = date(2008, 11, 10)
>>> time_tuple = dt.timetuple()
>>> print repr(time_tuple)
'time.struct_time(tm_year=2008, tm_mon=11, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=0, tm_yday=315, tm_isdst=-1)'
更多示例请参考此链接:http://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/
【讨论】:
请查看time Python module的文档,说明可以使用calendar.timegm或time.mktime将time.struct_time对象转换为纪元以来的秒数(使用哪个函数取决于你的struct_time是否在时区或 UTC 时间)。然后,您可以在另一个对象上使用datetime.datetime.time,并以秒为单位进行比较。
【讨论】:
使用“日期时间”中的strftime。它具有各种属性,并且可以使用指令获取相应的数据。有关可与 strftime method 一起使用的指令的完整列表,请参阅 this cheat-sheet。请注意,指令应作为单引号中的字符串传递给strftime。
例子:
import datetime as dt
today = dt.datetime.today()
print(today.strftime('%H')) #prints hour 0-23
print(today.strftime('%m')) #prints month number 1-12
print(today.strftime('%M')) #prints minute 0-59
【讨论】: