如何将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,d.weekday(),yday,-1))
,其中
yday = d.toordinal() - date(d.year,1,1).toordinal() + 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模块的文档,该文档指示您可以使用calendar.timegm或time.mktime将time.struct_time对象转换为自纪元以来的秒数(所使用的功能取决于struct_time是在时区还是在时区中)。在UTC时间)。然后,您可以在另一个对象上使用datetime.datetime.time,并比较自该纪元以来的秒数。