0

I am trying to create an array with the following, see this example for my objective.

Currently I have this code which calculates the amount of days in each month between two dates:

a = datetime(2019,11,1)
b = datetime(2023,12,31)
days = [calendar.monthrange(dt_i.year, dt_i.month)[1] for dt_i in rrule.rrule(rrule.MONTHLY, dtstart=a, until=b)]

OUTPUT

[30, 31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

OBJECTIVE:

What I am trying to accomplish is something similar but for years

a = datetime(2019,11,1)
b = datetime(2023,12,31)
##Unsure of code going here##

OUTPUT

[60, 366, 365, 365, 365]

With the goal of finding the remaining days in current year, then the days in the out years

Any help appreciated, thanks!

bathtub2007
  • 81
  • 1
  • 7

2 Answers2

1
from datetime import datetime

a = datetime(2019, 11, 1)
b = datetime(2023, 12, 31)

# end of a's year
next_a = datetime(2019, 12, 31)

# previous b's end year
prev_b = datetime(2022, 12, 31)

# get all full year difference in days
difs_in_years = [(datetime(x + 1, 12, 31) - datetime(x, 12, 31)).days for x in range(next_a.year, prev_b.year)]

# get a's diff in days from its end of the year
difs_in_years.insert(0, (next_a - a).days)

# get b's diff in days from its beggining of the year
difs_in_years.insert(len(difs_in_years), (b - prev_b).days)

print(difs_in_years)
nonamer92
  • 1,887
  • 1
  • 13
  • 24
1

ranisfisch beat me to it.

I was going to point out How to Calculate the number of days in the year(s) between 2 dates in python which is basically the same problem. Also, I'll point out that your days-per-month example only works if the start date is on the first of the month.

mermaldad
  • 322
  • 2
  • 7