简体   繁体   中英

ValueError: day is out of range for month python

I am writing code that lets users write down dates and times for things they have on. It takes in the date on which it starts, the start time and finish time. It also allows the user to specify if they want it to carry over into multiple weeks (every Monday for a month for example) I am using a for loop to do this, and because of the different months having different days I obviously want (if the next Monday for example is in the next month) it to have the correct date.

This is my code:

for i in range(0 , times):
    day = day
    month = month
    fulldateadd = datetime.date(year, month, day)
    day = day + 7
    if month == ( '01' or '03' or '05' or '07' or '10'or '12'):
        if day > 31:
            print(day)
            day = day - 31
            print(day)
            month = month + 1
        elif month == ( '04' or '06'or '09' or '11'):
            if day > 30:
                print(day)
                day = day - 30
                print(day)
                month = month + 1
        elif month == '02':
            if day > 29:
                print(day)
                day = day - 29
                print(day)
                month = month + 1

When running this and testing to see if it goes correctly into the new month I get the error:

  File "C:\Users\dansi\AppData\Local\Programs\Python\Python36-32\gui test 3.py", line 73, in addtimeslot
fulldateadd = datetime.date(year, month, day)
ValueError: day is out of range for month

Where have I gone wrong?

It's hard to be completely accurate without seeing some of the previous code (for example, where do day , month , year , and times come from?), but here's how you might be able to use timedelta in your code:

fulldateadd = datetime.date(year, month, day)
for i in range(times):
    fulldateadd = fulldateadd + datetime.timedelta(7)

A timedelta instance represents a period of time, rather than a specific absolute time. By default, a single integer passed to the constructor represents a number of days. So timedelta(7) gives you an object that represents 7 days.

timedelta instances can then be used with datetime or date instances using basic arithmetic. For example, date(2016, 12, 31) + timedelta(1) would give you date(2017, 1, 1) without you needing to do anything special.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM