如何从 pandas.Timedelta 对象获取毫秒

如果你有 pandas.Timedelta 对象,你可以使用 Timedelta.total_seconds() 获取具有毫秒分辨率的秒数作为浮点数,然后乘以十亿(1e3,一秒中的毫秒数)以获得 Timedelta 中的毫秒数:

timedelta_get_milliseconds.py
timedelta.total_seconds() * 1e3

如果你想要整数,使用

timedelta_milliseconds_int.py
int(round(timedelta.total_seconds() * 1e3))

注意此处需要使用 round() 以避免由于浮点精度导致的错误。

或使用此函数定义:

milliseconds_from_timedelta.py
def milliseconds_from_timedelta(timedelta):
    """以浮点数计算 timedelta 中的毫秒"""
    return timedelta.total_seconds() * 1e3

def milliseconds_from_timedelta_integer(timedelta):
    """以整数计算 timedelta 中的毫秒"""
    return int(round(timedelta.total_seconds() * 1e3))

# 用法示例:
ms = milliseconds_from_timedelta(timedelta)
print(ms) # 打印 2000.752
ms = milliseconds_from_timedelta_integer(timedelta)
print(ms) # 打印 2001

Check out similar posts by category: Pandas, Python