How to convert datetime.date object to time.struct_time object?

I have a python script that I need to compare with two dates. I have a list date as time.struct_time objects that I need to compare with multiple datetime.date objects.

How to convert datetime.date objects to time.struct_time objects? Or can I use them as a comparison?

+7
source share
3 answers

Try using date.timetuple() . From Python docs:

Return time.struct_time , e.g. time.struct_time time.localtime() returned. hours, minutes and seconds are 0 and the DST flag is -1. d.timetuple() equivalent to time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1)) , where yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 day number in the current year starting from January 1 to January 1.

+12
source

Example of converting date objects to time.struct_time objects:

 #### 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)' 

See this link for more details: http://www.saltycrane.com/blog/2008/11/python-datetime-time-conversions/

+1
source

Refer to the documentation for the Python module time , which indicates that you can use calendar.timegm or time.mktime to convert time.struct_time to the nearest second (the function you use depends on whether your struct_time is in the time zone or in UTC). Then you can use datetime.datetime.time on another object and compare in seconds from an era.

0
source

All Articles