The Wayback Machine - https://web.archive.org/web/20240906025359/https://www.geeksforgeeks.org/how-to-convert-timestamp-string-to-datetime-object-in-python/
Open In App

How to convert timestamp string to datetime object in Python?

Last Updated : 28 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:45
Explanation: In This, We are converting a timestamp string to a datetime object in Python.

Python Timestamp String to Datetime Object

Here are different methods to convert timestamp strings to datetime objects.

  • Using strptime()
  • Using datetime.strptime()
  • Using dateutil.parser.parse()
  • Using datetime.from timestamp()

Python timestamp to Datetime using strptime()

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 representation.

Python3




from datetime import datetime
 
timestamp_string = "2023-07-21 15:30:45"
format_string = "%Y-%m-%d %H:%M:%S"
datetime_object = datetime.strptime(timestamp_string, format_string)
print(datetime_object)


Output

2023-07-17  11:30:45

Python timestamp string to Datetime using datetime.strptime()

To get a DateTime in a particular form you can use strftime() function. You can simply use the form timestamp function from the Datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding Datetime object to the timestamp.

Python3




from datetime import datetime
 
 
timestamp = 1545730073
dt_obj = datetime.fromtimestamp(1140825600)
 
print("date_time:",dt_obj)
print("type of dt:",type(dt_obj))


Output

date_time: 2006-02-25 05:30:00
type of dt_obj: <class 'datetime.datetime'>

Python timestamp to Datetime using dateutil.parser.parse()

Here is an example of using Python’s the .parser.parse() . This function is a powerful and flexible tool for converting various date and time representations, including timestamps, to datetime objects. It is part of the Dateutil library.

Python3




from dateutil.parser import parse
 
timestamp_string = "2023-07-17  11:30:45"
 
datetime_object = parse(timestamp_string)
print(datetime_object)


Output

2023-07-17  11:30:45

Python timestamp to Datetime using Datetime.from timestamp()

Here, we have imported the Datetime class from the an Datetime module. Then we have used datetime.fromtimestamp() method returns a datetime an object representing the datetime corresponding to the given timestamp. 

Python3




import datetime
 
timestamp = 1690433696
 
# Convert timestamp to datetime object
dt_object = datetime.datetime.fromtimestamp(timestamp)
 
print(dt_object) 


Output

2023-07-27 04:54:56


Previous Article
Next Article

Similar Reads

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 UTC Timestamp in Python
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
3 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 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 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
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
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 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
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 remove timezone information from DateTime object in Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone. In this article, we will discuss how to remove timezone information from the DateT
2 min read
How to make a timezone aware datetime object in Python
In this example, we are going to see how to make a timezone-aware DateTime object in Python. Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is timezone aware or not: We can easily check if a d
4 min read
How to add time onto a DateTime object in Python
In this article, we will discuss the addition of time onto a specified DateTime object in Python. The effect of this will produce a new DateTime object. This addition can be performed by using datetime.timedelta() function. The timedelta() function is used for calculating differences in dates and also can be used for date manipulations in Python. I
2 min read
Add Years to datetime Object in Python
In this article let's learn how to add years to a datetime object in python. Python Datetime module supplies classes datetime. These classes provide us with 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
2 min read
Add Months to datetime Object in Python
In this article, let's delve into the techniques for Add Months to datetime Object in Python. Working with dates and times often requires manipulation and adjustment, and understanding how to add months to a datetime object is a crucial skill. We will explore various methods and libraries to achieve this task, providing you with a comprehensive gui
3 min read
Convert the column type from string to datetime format in Pandas dataframe
While working with data in Pandas, it is not an unusual thing to encounter time series data, and we know Pandas is a very useful tool for working with time-series data in Python.Let's see how we can convert a dataframe column of strings (in dd/mm/yyyy format) to datetime format. We cannot perform any time series-based operation on the dates if they
5 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
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
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
Pandas Series dt.quarter | Find Quarter from DateTime Object
Pandas dt.quarter attribute returns the quarter of the date in the underlying DateTime based data in the given Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr =
2 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
Article Tags :
Practice Tags :