Convert a pandas Timedelta object into a Python timedelta object


To convert a pandas Timedelta object into a Python timedelta object, use the timedelta.to_pytimedelta() method.

At first, import the required libraries −

import pandas as pd

Create a Timedelta object −

timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

Display the Timedelta −

print("Timedelta...\n", timedelta)

Convert a pandas Timedelta object into a python timedelta object. Any nanosecond resolution will be lost −

timedelta.to_pytimedelta()

Example

Following is the code −

import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# Convert a pandas Timedelta object into a python timedelta object
res = timedelta.to_pytimedelta()

# display the converted Timedelta object
# Any nanosecond resolution will be lost
print("\nTimedelta object after converting...\n", res)

Output

This will produce the following code −

Timedelta...
2 days 11:22:25.050000045

Timedelta object after converting...
2 days, 11:22:25.050000

Updated on: 14-Oct-2021

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements