Convert a Datetime to a UTC Timestamp in Python

Date-time objects are very important to know in Python, and datetime objects are a common task in programming languages. Datetime objects are mostly used when you are with the time data. It is also used when there is a need to work on different time zones; it is very important to convert a datetime object to a UTC timestamp. Python helps by converting datetime to UTC.

There are different ways to convert a datetime to a UTC timestamp in Python.

  1. Using datetime.timestamp()
  2. Using calender.timegm()
  3. Using pytz library
  4. Using time.mktime()

Convert A Datetime To A UTC Timestamp Using datetime.timestamp()

Let's see how to convert a datetime to a UTC timestamp with the help of datetime.timestamp() method.

Code:

Output:

Datetime: 2024-04-16 12:00:00
UTC Timestamp: 1713268800.0

Explanation:

In the above code, the datetime and timezone are imported from the datetime module. Date and time are passed to the datetime method and this date is replaced by the timezone UTC with the help of replace method.

Convert A Datetime To A UTC Timestamp Using calendar.timegm()

Let's see how to solve this problem with the help of a calendar.timegm() method.

Code:

Output:

Datetime: 2024-04-16 12:00:00
UTC Timestamp: 1713268800

Explanation:

In the above code, the calendar is imported, the datetime module is imported, and the current date and time are passed to the datetime object, and this date is converted to the UTC with the help of the calendar.timegm method and the current date and time is printed and its corresponding UTC timezone.

Convert A Datetime to a UTC Timestamp Using pytz Library:

Let's see an example demonstrating the method of converting a datetime to a UTC Timestamp with the help of the pytz library.

Code:

Output:

Datetime: 2024-01-25 12:00:00
UTC Timestamp: 1706184000

Explanation:

In the above code, the pytz module is imported, and the datetime object is created for the date 25 January 2024, and the time is 12 PM; this data and time is converted to the UTC timestamp with the help of time.mktime method. The original date and time and its UTC conversion are printed.

Another method is to convert the datetime to UTC timestamp; adjustment should be needed in mktime() method.

Convert A Datetime to a UTC Timestamp Using mktime() Method:

Let's see an example demonstrating the method of converting a datetime to a UTC Timestamp with the help of the mktime() method of the time module.

Code:

Output:

Datetime: 2024-04-17 06:55:00
UTC Timestamp: 1713317100

Explanation:

In the above code, time and datetime module is imported and current date and time is imported inside the datetime function, and this date and time is converted to the int and converted to the UTC timestamp.

Conclusion:

Python provides various functions and methods to convert a datetime to a UTC timestamp.