How to combine date and time into a Timestamp object in pandas
Overview
A Timestamp object in pandas is an equivalent of Python's datetime object. It is a combination of date and time fields.
To combine date and time into a Timestamp object, we use the Timestamp.combine() function in pandas.
Syntax
The syntax to combine date and time into a timestamp is:
Timestamp.combine(date, time)
Syntax for the Timestamp.combine() function
Parameters
The Timestamp.combine() function takes the following parameter values:
date: This is adatetime.dateobject representing the date field.time: This is adatetime.timeobject representing the time field.
Return value
The Timestamp.combine() function returns a Timestamp object formed from the combination of the date and time object.
Example
Let's look at the code below:
# A code to illustrate the Timestamp.combine() function in Pandas# impoting the pandas libraryimport pandas as pd# importing the date and time modulefrom datetime import date, time# creating a Timestamp object from the date and time combinationmy_datetime = pd.Timestamp.combine(date(2022, 4, 29), time(8,54,15))print(my_datetime)
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We import the
dateandtimemodules. - Line 10: We implement the
Timestamp.combine()function by combining thedateandtime. Thereby, we form adatetimeobject. We assign the value to a variable,my_datetime. - Line 12: We print the value of the variable,
my_datetime.