How to get microseconds from pandas.Timedelta object
If you have a pandas.Timedelta object, you can use Timedelta.total_seconds() to get the seconds as a floating-point number with microsecond resolution and then multiply with one million (1e6, the number of microseconds in one second) to obtain the number of microseconds in the Timedelta:
timedelta_get_microseconds.py
timedelta.total_seconds() * 1e6In case you want an integer, use
example.py
int(round(timedelta.total_seconds() * 1e6))Note that using round() is required here to avoid errors due to floating point precision.
or use this function definition:
example.py
def microseconds_from_timedelta(timedelta):
"""Compute the microseconds in a timedelta as floating-point number"""
return timedelta.total_seconds() * 1e6
def microseconds_from_timedelta_integer(timedelta):
"""Compute the microseconds in a timedelta as integer number"""
return int(round(timedelta.total_seconds() * 1e6))
# Usage example:
us = microseconds_from_timedelta(timedelta)
print(us) # Prints 2000751.9999999998
us = microseconds_from_timedelta_integer(timedelta)
print(us) # Prints 2000752If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow