Reputation: 255
I have a date time column in a Pandas DataFrame and I'd like to convert it to minutes or seconds.
For example: I want to convert 00:27:00
to 27 mins.
example = data['duration'][0]
example
result: numpy.timedelta64(1620000000000,'ns')
What's the best way to achieve this?
Upvotes: 25
Views: 39983
Reputation: 633
As noted by @ntg, using .astype('timedelta64[m]')
provides the result as an integer value, potentially reducing accuracy.
To obtain the result as a float value with full accuracy, we can scale the result to the desired units with np.timedelta64(1, 'm')
(see https://stackoverflow.com/a/20739897/12131616).
Example:
a = np.timedelta64(1621111111110,'ns')
print(a.astype('timedelta64[m]'))
print(a / np.timedelta64(1, 'm'))
Output:
27 minutes
27.0185185185
Upvotes: 1
Reputation: 3230
Use array.astype()
to convert the type of an array safely:
>>> import numpy as np
>>> a = np.timedelta64(1620000000000,'ns')
>>> a.astype('timedelta64[m]')
numpy.timedelta64(27,'m')
Upvotes: 48