Pandas Number Of Days Between Dates

How would I find the number of days between the current date and df['date'] and create a new column with the results.

date       count    user      days_since 
2013/02/22  145      apple      ###
2005/01/16  234      banana     ###
2011/02/01  521      orange     ###
2001/01/14  10       grape      ###

Thanks!

Posted May 11, 2013, 5:37 PM UTC

13
ryeguy146•

If you want to use the standard library, you can use the datetime module, but it's a bit awful. There's also arrow, a third party library for working with dates.

I've used datetime, essentially, you'd create a datetime.datetime from the date column, and then one of the current date, subtract one from the other to get a datetime.timedelta. From that you can extract seconds with the total_seconds method and use that to determine days. That's off the top of my head, I assume that the process could be done more efficiently.

2
zahlmanzahlman•

You can just ask the datetime.timedelta for its .days directly.

1
[deleted]•

[deleted]

1
sarver311•

I think that you can get this result nicely by using the apply method. What I would do is create a function that gets applied to each row in the date column, compares the date with todays date and returns the difference in days. Then you basically take the resulting output from that and assign it to your new column.

from datetime import datetime

def compare_dates(date):
    date_format = '%Y/%m/%d'
    current_date = datetime.strptime(date, date_format)  
    today = datetime.today()
    diff = current_date - today
    return diff.days

#apply this function to your pandas dataframe
df['days_since'] = df['date'].apply(compare_dates)

You should now have a new column with the days difference.

1