What is date.timetuple() in Python?

Overview

In Python, we need the datetime module to work with time and date objects. The datetime module consists of different classes and functions to operate with date and time.

Datetime involves date and time formatting, parsing, and arithmetic operators. The module also contains multiple constants like MAXYEAR and MINYEAR. Different instance functions and classes are also involved regarding date and time.

The timetuple method

We need to import the datetime module to use the timetuple() method. This method’s parameters can be accessed by the name and index of parameters. This object contains parameters for both date and time that are stored in tuples.

Date and time object related attributes

index

attibute

value

0

tm_year

(e-g, 1999)

1

tm_mon

range [1, 12]

2

tm_mday

range [1, 31]

3

tm_hour

[0, 23]

4

tm_min

[0, 59]

5

tm_sec

range [0, 61]

6

tm_wday

range [0, 6], 0 represents Monday

7

tm_yday

range [1, 366]

8

tm_isdst

0,1 or -1

N.A

tm_zone

Name of time zone

Syntax


timetuple()

Parameters

The timetuple() method does not take any parameters.

Return value

timetuple() returns the time.struct_time() object as a tuple that contains the date and time information, i.e., timestamps.

Note: This method is part of the time module and thus returns the object of time.

Explanation

The code below demonstrates how the timetuple() method works.

from datetime import date
## Create the instance
today = date(2019, 5, 12)
print("Date:", today)
time_tuple = today.timetuple()
# print time_tupe
print("\n date object's tuple:\n", time_tuple)
# printing elements as tuple
print("\nSpecific elements of this tuple can also be accessed: ")
attributes = ['tm_year', 'tm_mon','tm_mday', 'tm_hour',
'tm_min', 'tm_sec', 'tm_wday', 'tm_yday',
'tm_isdst']
i= 0
for t in time_tuple:
print(attributes[i], "=",t)
i+=1

Explanation

  • Line 3: We create an object of date type with (2019, 5, 12).
  • Line 5: We call the timetuple() method to get the time.struct_time object that contains a tuple of multiple values as shown in the table above.
  • Line 7: We print the time_tuple values to the console.
  • Line 10: We can see the list of all possible values in a tuple.
  • Line 14: We print the values of the time.struct_time object one by one to the console with their names in parallel.

Free Resources