Pandas Timestamp To Datetime
Last Updated :
06 Feb, 2024
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.
Converting Pandas Timestamps to Datetime Objects
Importing Pandas
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
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
ts = pd.Timestamp( "2024-02-05 10:00:00" )
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
ts = pd.Timestamp(year = 2024 , month = 1 , day = 28 , hour = 15 , minute = 30 , second = 0 , microsecond = 0 )
datetime_obj = ts.to_pydatetime()
print (datetime_obj)
print ( type (datetime_obj))
|
Output:
2024-01-28 15:30:00-05:00
<class 'datetime.datetime'>
Share your thoughts in the comments
Please Login to comment...