How to convert a Timestamp object in pandas to Python's datetime
Overview
The to_pydatetime() function in pandas converts a Timestamp object to the equivalent Python object, datetime.
Syntax
We can use to_pydatetime() function with the syntax below:
Timestamp.to_pydatetime()
Syntax for the to_pydatetime() function
Parameters
The to_pydatetime() function takes no parameter value other than the Timestamp object, which is to be converted to datetime.
Return value
The to_pydatetime() function returns a datetime object that returns the same date and time value from the input Timestamp object.
Example
# A code to illustrate the to_pydatetime() function in Pandas# importing the pandas libraryimport pandas as pd# creating a Timestamp objectmy_timestamp = pd.Timestamp("2022-05-01T10:30:52.192548")# printing the Timestamp objectprint(my_timestamp)# converting the Timestamp to python's datetime objectmy_datetime = my_timestamp.to_pydatetime()# printing the datetime objectprint(my_datetime)# checking the object typesprint(type(my_timestamp))print(type(my_datetime))
Explanation
- Line 4: We import the
pandaslibrary. - Line 7: We create a
Timestampobject,my_timestamp. - Line 10: We print the
Timestampobject,my_timestamp. - Line 13: We convert the
Timestampobject to adatetimeobject using theto_pydatetime()function and store the result inmy_datetime. - Line 16: We print the
datetimeobject,my_datetime. - Line 19–20: We use the
type()function to check for the object types ofmy_timestampandmy_datetime. We can see that they have different types but contain the same value of date and time.