如何从 pandas.Timedelta 对象获取微秒
如果你有 pandas.Timedelta 对象,你可以使用 Timedelta.total_seconds() 获取具有微秒分辨率的秒数作为浮点数,然后乘以一百万(1e6,一秒中的微秒数)以获得 Timedelta 中的微秒数:
timedelta_get_microseconds.py
timedelta.total_seconds() * 1e6如果你想要整数,使用
timedelta_microseconds_int.py
int(round(timedelta.total_seconds() * 1e6))注意此处需要使用 round() 以避免由于浮点精度导致的错误。
或使用此函数定义:
microseconds_from_timedelta.py
def microseconds_from_timedelta(timedelta):
"""以浮点数计算 timedelta 中的微秒"""
return timedelta.total_seconds() * 1e6
def microseconds_from_timedelta_integer(timedelta):
"""以整数计算 timedelta 中的微秒"""
return int(round(timedelta.total_seconds() * 1e6))
# 用法示例:
us = microseconds_from_timedelta(timedelta)
print(us) # 打印 2000751.9999999998
us = microseconds_from_timedelta_integer(timedelta)
print(us) # 打印 2000752If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow