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_get_milliseconds.py
timedelta.total_seconds() * 1e3In case you want an integer, use
example.py
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:
example.py
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 2001If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow