Incognito
Incognito

Reputation: 1953

How do I convert a datetime.date object into a time.struct_time object?

I have a python script which I need to compare two dates. I have a list dates as time.struct_time objects which I need to compare to a few datetime.date objects.

How do I convert the datetime.date objects into a time.struct_time objects? Or can I just use them as is for comparison?

Upvotes: 15

Views: 14775

Answers (4)

Dinesh
Dinesh

Reputation: 51

Use strftime from "datetime". It has various attributes and the respective data can be fetched using directives. See this cheat-sheet for a full list of directives that can be used with the strftime method. Note that the directives shall be passed to strftime as a string in single quotes.

Example:

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

Upvotes: 0

Sharan
Sharan

Reputation: 55

Example for 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)'

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

Upvotes: 1

Lucas Jones
Lucas Jones

Reputation: 20193

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

Return a time.struct_time such as returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple() is 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 is the day number within the current year starting with 1 for January 1st.

Upvotes: 21

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95509

Please see the documentation for the time Python module, which indicates that you can use calendar.timegm or time.mktime to convert the time.struct_time object to seconds since the epoch (which function you use depends on whether your struct_time is in a timezone or in UTC time). You can then use datetime.datetime.time on the other object, and compare in seconds since the epoch.

Upvotes: 0

Related Questions