python-3.xpandas

Find total number of days in a year (pandas)


Is there a way to calculate the total number of days in a year given a datetime format of YYYY-MM-DD in Pandas? I have explored dt.dayofyear but this function seem to provide the number of days from the start of the year until my datetime variable.

As an example, if my date is 2020-03-30, I should know that this is the year of 2020 and there are 366 days (leap year). If it is 2019-03-30, then it should return 365 days (non-leap year).

Tried to search through the pandas dt documentation but can't seem to find any.

Thanks.


Solution

  • I'm not sure if there's exactly a function to calculate the number of days given the year as input

    I would use this for calculating the number of days in any year:

    year=2020
    number_of_days = sum([pd.Period(f'{year}-{i}-1').daysinmonth for i in range(1,13)])
    

    but you can also use pd.Period and check for leap years

    import pandas as pd
    p = pd.Period('2020-03-30')
    if p.is_leap_year:
       days = 366
    else:
       days = 365
    print(days)
    

    both would OUTPUT for 2020:

    366