How to get milliseconds 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 millisecond resolution and then multiply with one billion (1e3
, the number of milliseconds in one second) to obtain the number of milliseconds in the Timedelta
:
timedelta.total_seconds() * 1e3
In case you want an integer, use
int(round(timedelta.total_seconds() * 1e3))
Note that using round()
is required here to avoid errors due to floating point precision.
or use this function definition:
def milliseconds_from_timedelta(timedelta):
"""Compute the milliseconds in a timedelta as floating-point number"""
return timedelta.total_seconds() * 1e3
def milliseconds_from_timedelta_integer(timedelta):
"""Compute the milliseconds in a timedelta as integer number"""
return int(round(timedelta.total_seconds() * 1e3))
# Usage example:
ms = milliseconds_from_timedelta(timedelta)
print(ms) # Prints 2000.752
ms = milliseconds_from_timedelta_integer(timedelta)
print(ms) # Prints 2001