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