23

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?

Julian F. Weinert
  • 7,474
  • 7
  • 59
  • 107
Behzad Shahbaz
  • 235
  • 1
  • 2
  • 5
  • I think you mean `27 mins`, not `87 mins`? o_O – l'L'l Oct 25 '14 at 19:13
  • 1
    In the general case, do you want the fractional part, too? E.g. if the input timedelta is `00:27:45`, do you want 27 or 27.75? – Warren Weckesser Oct 25 '14 at 19:22
  • I'm more interested in minutes as my data doesn't include seconds, so no I don't need the fraction. – Behzad Shahbaz Oct 25 '14 at 19:29
  • 1
    I figured you can get to the minutes by executing this line: mins = np.array([data['duration']], dtype = "timedelta64[m]")[0]. How can I append the values I receive in this array to my original data frame? – Behzad Shahbaz Oct 25 '14 at 19:30
  • see docs here: very easy in 0.15 http://pandas.pydata.org/pandas-docs/stable/timedeltas.html#frequency-conversion – Jeff Oct 25 '14 at 20:10

1 Answers1

46

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')
sebix
  • 2,943
  • 2
  • 28
  • 43
  • 1
    Note that this will loose accuracy (based on the comments, this is ok for the questor, but should be highlighted for the general question): try `np.timedelta64(1621111111110,'ns').astype('timedelta64[m]')` – ntg Aug 26 '22 at 04:28