Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
communitycreator

How to convert a Timestamp object in pandas to Python's datetime

Onyejiaku Theophilus Chidalu

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 library
import pandas as pd

# creating a Timestamp object
my_timestamp = pd.Timestamp("2022-05-01T10:30:52.192548")

# printing the Timestamp object
print(my_timestamp)

# converting the Timestamp to python's datetime object
my_datetime = my_timestamp.to_pydatetime()

# printing the datetime object
print(my_datetime)

# checking the object types
print(type(my_timestamp))
print(type(my_datetime))
Implementing the to_pydatetime() function

Explanation

  • Line 4: We import the pandas library.
  • Line 7: We create a Timestamp object, my_timestamp.
  • Line 10: We print the Timestamp object, my_timestamp.
  • Line 13: We convert the Timestamp object to a datetime object using the to_pydatetime() function and store the result in my_datetime.
  • Line 16: We print the datetime object, my_datetime.
  • Line 19–20: We use the type() function to check for the object types of my_timestamp and my_datetime. We can see that they have different types but contain the same value of date and time.

RELATED TAGS

pandas
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring