Converting Pandas Timestamps to Datetime Objects

Importing Pandas

Python3




import pandas as pd


Using the date() function

This method extracts the date information from the Timestamp object and returns a new datetime.date object. It’s useful if you only care about the date and not the time.

Python3




# Sample dataset using dictionaries
data = {
    'timestamp': ['2024-01-01 12:00:00', '2024-01-02 14:30:00', '2024-01-03 08:45:00'],
    'value': [10, 20, 15]
}
 
import pandas as pd
 
# Create a Timestamp object
ts = pd.Timestamp("2024-02-05 10:00:00")
 
# Extract the date using the date() method
date_obj = ts.date()
 
print(type(ts))
print(type(date_obj))


Output:

<class 'pandas._libs.tslibs.timestamps.Timestamp'>
<class 'datetime.date'>

Using the to_pydatetime() function

First, we create a timestamp object using Components (year, month, day, hour, minute, second, microsecond) and convert it to a DateTime object using the Pandas.to_pydatetime() function.

Python3




# Create a Pandas Timestamp object
ts =pd.Timestamp(year=2024, month=1, day=28, hour=15, minute=30, second=0, microsecond=0)
 
# Convert the Timestamp to a Python datetime object
datetime_obj = ts.to_pydatetime()
 
print(datetime_obj)
print(type(datetime_obj))


Output:

2024-01-28 15:30:00-05:00
<class 'datetime.datetime'>



Pandas Timestamp To Datetime

A timestamp is a representation of a specific point in time, expressed as a combination of date and time information. In data processing, timestamps are used to note the occurrence of events, record the time at which data was generated or modified, and provide a chronological ordering of data.

Pandas Timestamp is a data structure used to handle timestamps in time-series data analysis.

Similar Reads

Converting Pandas Timestamps to Datetime Objects

Importing Pandas...