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.total_seconds() * 1e6
In case you want an integer, use
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:
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 2000752