0

I have come across some examples that show how to calculate the difference between two dates using .days. However for some reason does not seem to be working for me. I have the following code:

import datetime
from datetime import date
dfPort = pd.read_csv('C:\\Research\\Lockup\\Data\\lockupdates.csv')
dfPort = pd.DataFrame(dfPort)
todaysDate=datetime.datetime.today()
dfPort['LDate']=pd.to_datetime(dfPort['LockupExpDate'], format='%m/%d/%Y')
dfPort['TimeLeft']=(todaysDate-dfPort['LDate']).days

I get the following error:

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

So I tried the following:

xx=dfPort['LDate']-todaysDate
xx.days

and got the same error message. The references in Stack Overflow that I was reading are: Difference between two dates in Python

How to fix?

FObersteiner
  • 16,957
  • 5
  • 24
  • 56
quinn
  • 81
  • 1
  • 10

1 Answers1

0

Your problem is because you are trying to access the days attribute directly on a Series Object. The result of subtracting the Series dfPort["LDate"] from todaysDate is a series of timedelta objects.

As @MrFruppes pointed out, there is a .dt property of the series that can be accessed. This returns a pandas.core.indexes.accessors.TimedeltaProperties object that exposes the TimeDelta members.

So the most performant solution would be:

dfPort['TimeLeft'] = (todaysDate-dfPort['LDate']).dt.days

Credit goes to @MrFruppes.

Below is my modified original answer, which are some examples of less-performance approaches [So you probably want to stop reading here.]


You could call the apply method of the series where you can access each member of the series like this:

dfPort['TimeLeft'] = (todaysDate-dfPort['LDate']).apply(lambda x: x.days)

Here is a list comprehension approach:

dfPort['TimeLeft'] = [v.days() for v in (todaysDate-dfPort['LDate'])]
BioData41
  • 697
  • 7
  • 14
  • 1
    You don't need an `apply` to access the days attribute of a timedelta Series. That's what the `dt` accessor is for! `apply` means an additional iteration, so less efficient - plus in many cases I think it is bad in terms of readability. A native Python list comprehension is the last thing you'll want to use when working with pandas because the built-in pandas methods are almost always more efficient. – FObersteiner Dec 07 '21 at 06:44