27

I have a column 'delta' in a dataframe dtype: timedelta64[ns], calculated by subcontracting one date from another. I am trying to return the number of days as a float by using this code:

from datetime import datetime
from datetime import date
df['days'] = float(df['delta'].days)

but I receive this error:

AttributeError: 'Series' object has no attribute 'days'

Any ideas why?

OllieP
  • 291
  • 1
  • 4
  • 9
  • You're calling a method on a Series (which is what a DataFrame column is) and not the values within it. Are you sure that the `dtype` of that column is already some sort of `datetime`? – cmaher Jul 07 '17 at 23:04
  • maybe you [need to convert it](https://stackoverflow.com/questions/18215317/extracting-days-from-a-numpy-timedelta64-value) – PRMoureu Jul 07 '17 at 23:07
  • Yes - Name: delta, dtype: timedelta64[ns] – OllieP Jul 07 '17 at 23:13

2 Answers2

49

DataFrame column is a Series, and for Series you need dt.accessor to calculate days (if you are using a newer Pandas version). You can see docs here

So, you need to change:

df['days'] = float(df['delta'].days)

To

df['days'] = float(df['delta'].dt.days)
Anna K.
  • 1,452
  • 12
  • 11
Aseem Ahir
  • 623
  • 1
  • 6
  • 7
  • The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – Trenton McKinney Sep 25 '19 at 18:14
  • 2
    This answered the question for me. The only addition I required was that dt refers to the datetime package so import datetime as dt. Perhaps this is obvious for experienced Pythonistas but I guess those who are searching for this might not be that experienced – James Oliver Nov 04 '19 at 14:07
  • 1
    specifically, "dt" DOES NOT refer to the datetime module - but an 'accessor' for 'datetimelike' objects of the Series values. the link provided explains it perfectly. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html that functionality is very, very subtle in my opinion, and i thank those for posting it. i used it to make a mask for datetimes that matched a certain weekday value. – dave campbell Dec 22 '20 at 03:32
17

While subtracting the dates you should use the following code.

df = pd.DataFrame([ pd.Timestamp('20010101'), pd.Timestamp('20040605') ])
(df.loc[0]-df.loc[1]).astype('timedelta64[D]')

So basically use .astype('timedelta64[D]') on the subtracted column.

howard roark
  • 628
  • 7
  • 27
  • this didn't work for me - its just sets all values to 0 (because time < 1 day); but I am on an older pandas version so who knows whats going on – n3rd Nov 01 '18 at 15:25