1

I would like to convert data of type timedelta64 in a Pandas Series into timedelta64 to hours.

To do this I'd like to access the .seconds or .days attribute of a timedelta64 so that I can convert these unit myself as per this SO post.

However, when I select the data using df['col'] I get an attribute error when I try to use .seconds or .days despite its dtype being <m8[ns] (which I believe represents timedelta64).

Is there another step that I need to do?

Community
  • 1
  • 1
Jason
  • 4,346
  • 10
  • 49
  • 75

1 Answers1

3

That question is referring to the built-in Python timedelta object, while you are dealing with a numpy array of timedelta64 values. See this question - you can convert to hours or seconds using astype.

td.astype('timedelta64[D]')
td.astype('timedelta64[s]')

Alternatively, you could divide by the appropriate unit.

td / np.timedelta64(1, 'D')
td / np.timedelta64(1, 's')
Community
  • 1
  • 1
chrisb
  • 49,833
  • 8
  • 70
  • 70
  • Thanks, both approaches worked. Is there any difference between the two methods or is it purely a matter or personal preference? @chrisb – Jason Sep 23 '14 at 19:32
  • 1
    @Bprodz - couldn't tell you for sure, but both should give the same answer. On some test data, astype was a little faster (and probably communicates the intent more clearly) so that may be the way to go. – chrisb Sep 23 '14 at 21:47