Python calendar.timegm() Function



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.

Syntax

Following 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 Value

This function returns an integer representing the corresponding timestamp.

Example: Converting UTC Time Tuple to Timestamp

In 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: 1741955400

Example: 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: 946684800

Example: 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
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy