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

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

timedelta_get_nanoseconds.py
timedelta.total_seconds() * 1e9

如果你想要整数,使用

timedelta_nanoseconds_int.py
int(round(timedelta.total_seconds() * 1e9))

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

或使用此函数定义:

nanoseconds_from_timedelta.py
def nanoseconds_from_timedelta(timedelta):
    """以浮点数计算 timedelta 中的纳秒"""
    return timedelta.total_seconds() * 1e9

def nanoseconds_from_timedelta_integer(timedelta):
    """以整数计算 timedelta 中的纳秒"""
    return int(round(timedelta.total_seconds() * 1e9))

# 用法示例:
ns = nanoseconds_from_timedelta(timedelta)
print(ns) # 打印 2000751999.9999998

ns = nanoseconds_from_timedelta_integer(timedelta)
print(ns) # 打印 2000752000

Check out similar posts by category: Pandas, Python