-2

I need a function to count the total number of days in the 'days' column between a start date of 1st Jan 1995 and an end date of 31st Dec 2019 in a dataframe taking leap years into account as well.

Example: 1st Jan 1995 - Day 1, 1st Feb 1995 - Day 32 .......and so on all the way to 31st.

enter image description here

PApostol
  • 2,152
  • 2
  • 11
  • 21
Dera
  • 13
  • 2
  • 1
    Is this a [tag:pandas] question? If so please add the `pandas` tag. Subtract from a `date` object that represents your reference date, get the number of days from the resulting `timedelta`s, add one? Did you [try anything](/help/minimal-reproducible-example)? Did you do [any research](//meta.stackoverflow.com/a/261593/843953)? [How to make good reproducible pandas examples](//stackoverflow.com/q/20109391/843953) – Pranav Hosangadi Nov 07 '22 at 22:30
  • Does this answer your question? [How to calculate number of days between two given dates](https://stackoverflow.com/questions/151199/how-to-calculate-number-of-days-between-two-given-dates) – PApostol Nov 07 '22 at 22:30
  • Does this answer your question? [Add column with number of days between dates in DataFrame pandas](https://stackoverflow.com/questions/22132525/add-column-with-number-of-days-between-dates-in-dataframe-pandas) – Pranav Hosangadi Nov 07 '22 at 22:30

1 Answers1

0

If you want to filter a pandas dataframe using a range of 2 date you can do this by:

start_date = '1995/01/01'
end_date   = '1995/02/01'
df = df[ (df['days']>=start_date) & (df['days']<=end_date) ]

and with len(df) you will see the number of rows of the filter dataframe.

Instead, if you want to calculate a range of days between 2 different date you can do without pandas with datetime:

from datetime import datetime
start_date = '1995/01/01'
end_date   = '1995/02/01'
delta = datetime.strptime(end_date, '%Y/%m/%d') - datetime.strptime(start_date, '%Y/%m/%d')
print(delta.days)

Output:

31

The only thing is that this not taking into account leap years

Will
  • 1,619
  • 5
  • 23