将 pandas Timedelta 对象转换为 Python timedelta 对象


要将 pandas Timedelta 对象转换为 Python timedelta 对象,请使用 timedelta.to_pytimedelta() 方法。

首先,导入所需的库 −

import pandas as pd

创建一个 Timedelta 对象 −

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

显示 Timedelta −

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

将 pandas Timedelta 对象转换为 python timedelta 对象。所有纳秒分辨率将丢失 −

timedelta.to_pytimedelta()

示例

以下是代码 −

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)

输出

这将生成以下代码 −

Timedelta...
2 days 11:22:25.050000045

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

更新日期:14-10-2021

663 次浏览

启动你的 职业生涯

完成课程并获得认证

开始
广告