Home > Software engineering >  ValueError: day is out of range for month - How to do math with dates that are in different months
ValueError: day is out of range for month - How to do math with dates that are in different months

Time:11-30

I have a python program that takes as input the week of the year in the format: YYYY-W# The program uses this input to generate values for each day of the week and output data to an excel file.

I am getting the error: ValueError: day is out of range for month and I realized I am getting this error when days of the week are in separate months (for example monday, tuesday are November, wednesday, thurday etc. are December).

The following code is how I get the values for days of the week:

monday = datetime.datetime.strptime(week   '-1', '%G-W%V-%u')
tuesday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   1)
wednesday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   2)
thursday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   3)
friday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   4)
saturday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   5)
sunday = datetime.datetime(monday.year, monday.month, monday.day - monday.weekday()   6)

This code works fine if the entire week is within the same month, is there a way to modify this to account for weeks that may not all be within the same month?

CodePudding user response:

Use timedelta:

tuesday = monday   datetime.timedelta(days=1)
wednesday = ... # (and so on)

CodePudding user response:

Combining the answer in the (slight) duplicate question of Get date from week number and the answer from Rustam A.:

from datetime import datetime, timedelta

d = "2021-W48"
monday = datetime.strptime(d   "-1", "%Y-W%W-%w")
week = [monday   timedelta(days=x) for x in range(7)]

print(week)
# [datetime.datetime(2021, 11, 29, 0, 0), datetime.datetime(2021, 11, 30, 0, 0), datetime.datetime(2021, 12, 1, 0, 0), datetime.datetime(2021, 12, 2, 0, 0), datetime.datetime(2021, 12, 3, 0, 0), datetime.datetime(2021, 12, 4, 0, 0), datetime.datetime(2021, 12, 5, 0, 0)]

(edit: when using ISO-weeks, do you %G-W%V-%u as you did)

  • Related