Function Name:
timetuple
Function Signature:
timetuple()
Function Overview:
- The timetuple() method of datetime.date instances returns an object of type time.struct_time.
- The struct_time is a named tuple object. A named tuple object has attributes that can be accessed by an index or by name.
- The struct_time object has attributes for representing both date and time fields along with a flag to indicate whether Daylight Saving Time is active.
- The named tuple returned by the timetuple() function will have its year, month and day fields set as per the date object and fields corresponding to the hour, minutes, seconds will be set to zero.
- The returned object will have its DST flag set to the value of -1.
Example 1:
# import python's datetime module import datetime
# Create today's date todaysDate = datetime.date.today()
# Print Today's date print("Today's date is {}".format(todaysDate))
# Create a struct_time tuple out of today's date timeTuple = todaysDate.timetuple()
# Print the struct_time tuple print(timeTuple)
|
Output 1:
Today's date is 2017-02-09 time.struct_time(tm_year=2017, tm_mon=2, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=40, tm_isdst=-1) |
The fields
tm_year,
tm_mon,
tm_mday,
tm_hour,
tm_min,
tm_sec,
tm_wday,
tm_yday,
tm_isdst
can either be accessed using dateobject.attribute_name way are the
subscript way dateobject[0], dateobject[1] and so on.
The week of the day attribute tm_wday field will have the following values
0 – Sunday
1 – Monday
2 – Tuesday
3 – Wednesday
4 – Thursday
5 – Friday
6 – Saturday
Example 2:
# import python's datetime module import datetime
# Create Christmas date xmasDate = datetime.date(2017,12,25)
# Print Christmas date print("Christmas date is {}".format(xmasDate))
# Create a struct_time tuple out of Christmas date xmasTuple = xmasDate.timetuple()
# Print the struct_time tuple print("Christmas Year:{}".format(xmasTuple[0])) print("Christmas Month:{}".format(xmasTuple[1])) print("Christmas Date:{}".format(xmasTuple[2])) print("Christmas Hour:{}".format(xmasTuple[3])) print("Christmas Minutes:{}".format(xmasTuple[4])) print("Christmas Seconds:{}".format(xmasTuple[5])) print("Christmas Day of the Week:{}".format(xmasTuple[6])) print("Christmas Day of the Year:{}".format(xmasTuple[7])) print("DST Flag:{}".format(xmasTuple[8]))
|
Output 2:
Christmas date is 2017-12-26 Christmas Year:2017 Christmas Month:12 Christmas Date:26 Christmas Hour:0 Christmas Minutes:0 Christmas Seconds:0 Christmas Day of the Week:1 Christmas Day of the Year:360 DST Flag:-1 |