The Wayback Machine - https://web.archive.org/web/20241128023640/https://www.geeksforgeeks.org/convert-datetime-to-utc-timestamp-in-python/
Open In App

Convert Datetime to UTC Timestamp in Python

Last Updated : 29 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Dealing with datetime objects and timestamps is a common task in programming, especially when working with time-sensitive data. When working with different time zones, it's often necessary to convert a datetime object to a UTC timestamp. In Python, there are multiple ways to achieve this. In this article, we will explore four different methods for converting a DateTime to a UTC timestamp.

Convert A Datetime To A Utc Timestamp In Python

Below, are the ways to Convert A Datetime To A Utc Timestamp In Python.

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

In this example, the DateTimebelow code creates a datetime object `dt` representing January 25, 2024, 12:00 PM. It then converts this datetime object to a UTC timestamp using the `replace()` method to set the timezone to UTC and the `timestamp()` method to obtain the POSIX timestamp.

Python3
from datetime import datetime, timezone

# Create a datetime object
dt = datetime(2024, 1, 25, 12, 0, 0)

# Convert to UTC timestamp using timestamp() method
timestamp_utc = dt.replace(tzinfo=timezone.utc).timestamp()

print("Datetime:",dt)
print("UTC Timestamp:", timestamp_utc)

Output :

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

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

In this example, below code utilizes the `calendar` module and `timegm()` function to convert a datetime object `dt` (representing January 25, 2024, 12:00 PM) to a UTC timestamp. It extracts the UTC time tuple from the datetime object using `utctimetuple()` and then employs `timegm()` to calculate the UTC timestamp.

Python3
import calendar
from datetime import datetime

# Create a datetime object
dt = datetime(2024, 1, 25, 12, 0, 0)

# Convert to UTC timestamp using timegm() function
timestamp_utc = calendar.timegm(dt.utctimetuple())

print("Datetime:", dt)
print("UTC Timestamp:", timestamp_utc)

Output :

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

Convert A Datetime To A Utc Timestamp Using pytz library

In this example, below code uses the `pytz` library to convert a datetime object `dt` (representing January 25, 2024, 12:00 PM) to a UTC timestamp. It first localizes the datetime object to the UTC timezone using `pytz.utc.localize()`. Then, it obtains the UTC timestamp by converting the localized datetime object using the `timestamp()` method.

Python3
import pytz
from datetime import datetime

# Create a datetime object
dt = datetime(2024, 1, 25, 12, 0, 0)

# Set the timezone to UTC
dt_utc = pytz.utc.localize(dt)

# Convert to UTC timestamp
timestamp_utc = int(dt_utc.timestamp())

print("Datetime:", dt)
print("UTC Timestamp:", timestamp_utc)

Output :

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

Convert A Datetime To A Utc Timestamp Using time.mktime()

In this example, below code creates a datetime object for January 25, 2024, 12:00 PM, and then converts it to a UTC timestamp using the `time.mktime` function. The original datetime and its corresponding UTC timestamp are printed. This method assumes the datetime object is in the UTC timezone or doesn't require timezone adjustment before applying `mktime()`.

Python3
import time
from datetime import datetime

# Create a datetime object
dt = datetime(2024, 1, 25, 12, 0, 0)

# Convert to UTC timestamp using time.mktime
timestamp_utc = int(time.mktime(dt.timetuple()))

print("Datetime:", dt)
print("UTC Timestamp:", timestamp_utc)

Output :

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

Conclusion

In conclusion, Python offers various methods to convert a datetime object to a UTC timestamp, catering to different preferences and use cases. Whether utilizing built-in functions such as timestamp() or time.mktime, employing libraries like pytz or arrow, or even relying on manual mathematical operations, developers can choose the approach that best fits their coding style and project requirements.


Previous Article
Next Article

Similar Reads

Get UTC timestamp in Python
Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps. Note: For more information, refer to Python datetime module
1 min read
Ensuring timestamp storage in UTC with SQLAlchemy
In modern web applications, handling timestamps is a common requirement. Storing timestamps in a standardized format, such as UTC (Coordinated Universal Time), ensures consistency and simplifies data manipulation across different time zones. This article explores best practices and provides a step-by-step implementation guide for storing timestamps
4 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
How to Convert DateTime to UNIX Timestamp in Python ?
The Unix timestamp is a single signed integer that grows by one every second, allowing computers to store and manipulate conventional date systems. The software is then translated into a human-readable format. The Unix timestamp is the number of seconds calculated since January 1, 1970. In this article, we are going to see how to convert DateTime t
5 min read
Convert datetime to unix timestamp in SQLAlchemy model
When dealing with databases date and time are considered to be one of the most important attributes for any entity. With such data, we often encounter some common task of converting DateTime to a Unix timestamp. In this article, we will learn how we can convert datetime to Unix timestamp in SQLAlchemy. Converting Datetime to Unix TimeStamp in SQLal
5 min read
Python | Pandas Timestamp.timestamp
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That z
3 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
Python datetime to integer timestamp
In this article, we are going to see how to convert python DateTime to integer timestamp. The timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That zero moment is known as the epoch. First, we will get the current time or explicitly mention the required date and time we want the timest
3 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Convert date string to timestamp in Python
The Most Common way we use to store dates and times into a Database is in the form of a timestamp. date and time in form of a string before storing it into a database, we convert that date and time string into a timestamp. Python provides various ways of converting the date to timestamp. Few of them discussed in this article are: Using timetuple()U
2 min read
Python Pandas - Convert PeriodIndex object to Timestamp and set the frequency
In this article, we will discuss how to convert period index objects to timestamp and set the frequency in the python programming language. The pandas PeriodIndex.to_timestamp() method is used to convert a PeriodIndex object to Timestamp and set the frequency. frequency can be set using the 'freq' parameter of the method. Example 1: Pandas package
3 min read
How to convert NumPy datetime64 to Timestamp?
In this article, we will discuss how to convert NumPy datetime64 to Timestamp in Python.Example: Input: If the current datetime64 is as follows: 2020-08-18 09:31:51.944622 Output: The required timestamp in seconds will be: 1597743111.944622 The required timestamp in minutes will be: 26629051.8657437 The required timestamp in an hour will be: 443817
2 min read
How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately. Here, we deal with a special date objec
2 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Convert Python datetime to epoch
In this article, we are going to discuss various ways by which we can convert Python DateTime to epoch. The epoch time is also known as POSIX time which will indicate the number of seconds passed from January 1, 1970, 00:00:00 (UTC) in most Windows and Unix systems. Note: Epoch is platform-dependent which means it depends on the system or operating
4 min read
How to convert datetime to date in Python
In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt.date from Pandas in Python. Method 1: Convert DateTime t
3 min read
Convert string to datetime in Python with timezone
Prerequisite: Datetime module In this article, we will learn how to get datetime object from time string using Python. To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. Syntax : datetime.strptime(date_string, format) Parameters : date_string : Specified tim
3 min read
Python - Convert excel serial date to datetime
This article will discuss the conversion of an excel serial date to DateTime in Python. The Excel "serial date" format is actually the number of days since 1900-01-00 i.e., January 1st, 1900. For example, the excel serial date number 43831 represents January 1st, 2020, and after converting 43831 to a DateTime becomes 2020-01-01. By using xlrd.xldat
3 min read
Convert Date To Datetime In Python
When you're programming, dealing with dates and times is important, and Python provides tools to manage them well. This article is about changing dates into date times in Python. We'll explore methods that can help you switch between these two types of data. Whether you're building a website or working with data, mastering this conversion skill is
3 min read
How to Convert Integer to Datetime in Pandas DataFrame?
Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check data type for the 'Dates' column is Integer. Python
2 min read
How to Convert Float to Datetime in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=
3 min read
How to Convert Datetime to Date in Pandas ?
DateTime is a collection of dates and times in the format of "yyyy-mm-dd HH:MM:SS" where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time. In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime using the Pandas Python module. Syntax: yyyy-mm-dd H
4 min read
Pandas Series dt.to_period() Method | Convert DateTime to Period Format
The Pandas dt.to_period() method converts the underlying data of the given Series object to PeriodArray/Index at a particular frequency. It is used to convert a DateTime series to a period series with a specific frequency, such as daily, monthly, quarterly, or yearly periods. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '201
2 min read
Pandas Series dt.tz_localize() | Convert tz-Naive DateTime to tz-Aware
The dt.tz_localize() method converts the time zone (tz)-naive Datetime Series object into a tz-aware Datetime Series. It does not move the time to another time zone. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
How to Convert String to Date or Datetime in Polars
When working with data, particularly in CSV files or databases, it's common to find dates stored as strings. If we're using Polars, a fast and efficient DataFrame library written in Rust (with Python bindings), we'll often need to convert these strings into actual date or datetime objects for easier manipulation and analysis. In this article, we'll
5 min read
Python | Pandas Timestamp.second
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.second attribute return an integer value which represents the value of second in the given Timestamp object. Syntax : T
2 min read
Python | Pandas Timestamp.date
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.date() function return a datetime object with same year, month and day as that of the given Timestamp object. Syntax :
2 min read
Python | Pandas Timestamp.ctime
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.ctime() function return the time in string format. The format of the returned string object is based on ctime() style.
2 min read
three90RightbarBannerImg