python - 使用 timedelta.round() 函数

标签 python datetime timedelta python-datetime

我已经看到多个关于如何定义自己的函数来执行与此类似的操作的问题,但我不知道如何使用 timedelta 的内置函数。有没有人有使用 timedelta.round() 的例子?我有 timedelta 对象,我想四舍五入到最接近的全天。

文档位于 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.round.html是:

Timedelta.round

Round the Timedelta to the specified resolution

Parameters:

freq : a freq string indicating the rounding resolution

Returns: a new Timedelta rounded to the given resolution of freq

Raises: ValueError if the freq cannot be converted

最佳答案

这个问题已经回答了,但我把它放在一个 MWE 中以便更好地理解:

import pandas as pd
df = pd.Series(pd.to_timedelta([
        '0 days +01:01:02.123',
        '0 days +04:03:04.651']))
df.dt.round('5s')  #Rounds to 5sec

输出将是:

0   01:01:00
1   04:03:05
dtype: timedelta64[ns]

其他有用且相关的问题(timedelta 在用法上类似于 datetime):

关于python - 使用 timedelta.round() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51661280/

相关文章:

sql - 我想要小时,分钟,两个日期时间的第二个差异

php - 选择具有特定日期的行

Python,日期时间 "time gap"百分比

python - 使用表单集前缀时缺少 ManagementForm 数据

python - 在python中计算表面拟合后3D偏差的均方根

python - 是什么导致该套接字运行速度非常慢?

python - 根据时间将值拆分到容器中

python - 为什么我不能将 datetime.timedelta 除以 float ?

C++ high_resolution_clock 奇怪的输出

python - 二维中一组 N 个点之间的有向距离