[英]ValueError: day is out of range for month - How to do math with dates that are in different months
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.我有一个 python 程序,它将一年中的一周作为输入,格式为:
YYYY-W#
该程序使用此输入为一周中的每一天生成值,并将 output 数据生成到 ZBF57C906FA7D2BB66D07372E4158 文件。
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).我收到错误:
ValueError: day is out of range for month
,我意识到当一周中的几天在不同的月份(例如,星期一、星期二是 11 月,星期三、星期四等是 12 月)时,我收到了这个错误。
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?如果整个星期都在同一个月内,则此代码可以正常工作,有没有办法修改它以考虑可能不在同一个月内的几周?
Combining the answer in the (slight) duplicate question of Get date from week number and the answer from Rustam A.:结合Get date from week number的(轻微)重复问题中的答案和 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 use %GW%V-%u
as you did) (编辑:使用 ISO 周时,请像您一样使用
%GW%V-%u
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.