The timetuple() method in Python's datetime module returns a named tuple, time.struct_time, containing various components of a date and time object. This method is particularly useful for extracting detailed information from date and datetime objects.
The time.struct_time tuple includes the following attributes:
from datetime import date
dt = date.today().timetuple()
print(dt)
Output
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=16, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=0, tm_yday=259, tm_isdst=-1)
Getting time details along with date
from datetime import datetime
dt = datetime.now().timetuple()
print(dt)
Output is here
time.struct_time(tm_year=2019, tm_mon=9, tm_mday=17, tm_hour=6,
tm_min=18, tm_sec=26, tm_wday=1, tm_yday=260, tm_isdst=-1)
import datetime
dt = datetime.datetime(2019, 12, 31)
print(dt.timetuple())
Output
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=31, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=365, tm_isdst=-1)
Using datetime
import datetime
# Year, Month, Date, Hour, Minute, Second, Microsecond
dt = datetime.datetime(2019, 12, 31, 23, 59, 59, 345234)
print(dt.timetuple())
Output
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=31, tm_hour=23,
tm_min=59, tm_sec=59, tm_wday=1, tm_yday=365, tm_isdst=-1)
print(len(dt.timetuple()))
output
9
Value of 2nd element i.e date part of the object. ( first element position is 0 )
print(dt.timetuple()[2])
Output is 31
Displaying all values by looping.
for i in dt.timetuple():
print(i)
Output is here
2019
12
31
23
59
59
1
365
-1
Let's create a datetime object and extract its components using the timetuple() method:
from datetime import datetime
dt = datetime(2025, 2, 8, 14, 30, 45)
tt = dt.timetuple()
print(f"Year: {tt.tm_year}")
print(f"Month: {tt.tm_mon}")
print(f"Day: {tt.tm_mday}")
print(f"Hour: {tt.tm_hour}")
print(f"Minute: {tt.tm_min}")
print(f"Second: {tt.tm_sec}")
print(f"Weekday: {tt.tm_wday}")
print(f"Day of the year: {tt.tm_yday}")
print(f"DST flag: {tt.tm_isdst}")
We can convert a datetime object to a timestamp using the timetuple() method in conjunction with the time module:
from datetime import datetime
import time
dt = datetime(2025, 2, 8, 14, 30, 45)
timestamp = time.mktime(dt.timetuple())
print(f"Timestamp: {timestamp}")
The timetuple() method can be used with strftime() to format datetime objects into readable strings:
from datetime import datetime
dt = datetime(2025, 2, 8, 14, 30, 45)
formatted_date = dt.strftime("%A, %B %d, %Y %I:%M:%S %p")
print(f"Formatted Date: {formatted_date}")
The timetuple() method is beneficial in scenarios such as:
By leveraging the timetuple() method, we can efficiently dissect and utilize the components of date and time objects in Python, enhancing our ability to perform precise time-based computations and formatting.