-2

For example:

day of year: 365

Results:

day: 31
month: 12

2 Answers2

0

date and time related things should always be handled by the datetime package to account for leap years and similar shenanigans. For example, 2020 is a leap year.

"""calculate day and month from day of year"""
from datetime import datetime, timedelta

TOTAL_DAYS = 365
YEAR = 2020

startDate = datetime(year=YEAR, month=1, day=1)
daysToShift = TOTAL_DAYS - 1
endDate = startDate + timedelta(days=daysToShift)

month = endDate.month
day = endDate.day

print(f"Day {TOTAL_DAYS} corresponds to day {day} of month {month}.")

The output of the code above is:

Day 365 corresponds to day 30 of month 12.

If you choose 2019, it is day 31.

PotatoesFall
  • 345
  • 2
  • 7
-1

initialize a date variable with value december 31, and add x days. then take the date and month out of the result