The Python calendar.timegm() function is used to convert a time tuple in UTC to a timestamp (seconds since epoch).
This function is the inverse of time.gmtime(), which converts a timestamp to a time tuple.
SyntaxFollowing is the syntax of the Python calendar.timegm() function −
timestamp = calendar.timegm(time_tuple)Parameters
This function accepts a tuple of 9 elements as a parameter representing a UTC time (year, month, day, hour, minute, second, weekday, day of the year, DST flag).
Return ValueThis function returns an integer representing the corresponding timestamp.
Example: Converting UTC Time Tuple to TimestampIn this example, we convert a specific UTC time tuple to a timestamp using the calendar.timegm() function −
import calendar time_tuple = (2025, 3, 14, 12, 30, 0, 4, 73, 0) # March 14, 2025, 12:30:00 UTC timestamp = calendar.timegm(time_tuple) print("Timestamp:", timestamp)
Following is the output of the above code −
Timestamp: 1741955400Example: Converting Current UTC Time to Timestamp
We can use the time.gmtime() function to get the current UTC time tuple and convert it −
import calendar import time # Get current UTC time tuple time_tuple = time.gmtime() timestamp = calendar.timegm(time_tuple) print("Current UTC Timestamp:", timestamp)
Following is the output obtained −
Current UTC Timestamp: 1741955400 # (Example output, varies based on current time)Example: Converting a Past Date to Timestamp
We can also convert past dates to timestamps as shown in the example below −
import calendar time_tuple = (2000, 1, 1, 0, 0, 0, 5, 1, 0) # January 1, 2000, 00:00:00 UTC timestamp = calendar.timegm(time_tuple) print("Timestamp for Y2K:", timestamp)
We get the output as shown below −
Timestamp for Y2K: 946684800Example: Converting a Future Date to Timestamp
We can convert a future date, such as January 1, 2050, to a timestamp as shown in the following example −
import calendar time_tuple = (2050, 1, 1, 0, 0, 0, 5, 1, 0) # January 1, 2050, 00:00:00 UTC timestamp = calendar.timegm(time_tuple) print("Timestamp for 2050:", timestamp)
The result produced is as shown below −
Timestamp for 2050: 2524608000
python_date_time.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4