简体   繁体   English

ValueError:日期超出月份日期时间的范围

[英]ValueError: day is out of range for month datetime

I have run into a problem with some code I have been writing.我在编写一些代码时遇到了问题。 I take in four inputs ( day, month and year ) as a date, and times for how many times they want to repeat the task ( eg. every Monday for 3 weeks ).我将四个输入(日、月和年)作为日期,以及他们想要重复任务的次数(例如,每周一持续 3 周)。 The code is great however if the weeks differ between months I get this error:代码很棒,但是如果几个月之间的周数不同,我会收到此错误:

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

Part of code that is relevant:相关的部分代码:

for i in range(0 , times):
    fulldateadd = datetime.date(year, month, day)
    cursor.execute( '''INSERT INTO dates (Date, Name, Start, End) VALUES( ?,?,?,? );''', (fulldateadd , name1, starttimehour, endtimehour))
    day = day + 7
    if day > 31:
        month = month + 1

I've tried to increment the month when the number of days are more than 31 however it doesn't seem to work.当天数超过 31 时,我试图增加月份,但它似乎不起作用。

There are several reasons why incrementing the components of a datetime and then creating a new one is not a good idea.增加日期时间的组件然后创建一个新的组件不是一个好主意的原因有几个。 Primarily because dealing with the Gregorian calendar yourself isn't that enjoyable IMHO, and datetime objects can do it for you.主要是因为您自己处理公历并不是那么令人愉快,恕我直言,日期时间对象可以为您完成。

On that note, a much more straightforward approach would be to add a timedelta to your datetime within the loop.在这一点上,一个更直接的方法是在循环中为您的日期时间添加一个时间增量。 For instance,例如,

>>> from datetime import timedelta
>>> times = 4
>>> cur_date = datetime.date(2017, 2, 24)

>>> for _ in range(times):
        print('today is {0}, do something'.format(cur_date))
        cur_date += timedelta(days=7)

today is 2017-02-24, do something
today is 2017-03-03, do something
today is 2017-03-10, do something
today is 2017-03-17, do something

This could be placed in a generator as well, depending on your use case.这也可以放置在生成器中,具体取决于您的用例。

>>> for dt in (cur_date + timedelta(days=x*7) for x in range(times)):
        print('today is {0}, do something'.format(dt))

today is 2017-02-24, do something
today is 2017-03-03, do something
today is 2017-03-10, do something
today is 2017-03-17, do something

or with Pandas pd.date_range或使用 Pandas pd.date_range

>>> import pandas as pd
>>> list(pd.date_range(start='2017-02-24', periods=4, freq='7D'))

[Timestamp('2017-02-24 00:00:00', freq='7D'),
 Timestamp('2017-03-03 00:00:00', freq='7D'),
 Timestamp('2017-03-10 00:00:00', freq='7D'),
 Timestamp('2017-03-17 00:00:00', freq='7D')]

Now what would happen if you attempted this example with your approach?现在如果你用你的方法尝试这个例子会发生什么?

>>> year, month, day = 2017, 2, 24

>>> for i in range(0 , times):
        day = day
        fulldateadd = datetime.date(year, month, day)
        print('today is {0}, do something'.format(fulldateadd))
        day = day + 7
        if day > 31:
            day = day - 31
            month = month + 1

today is 2017-02-24, do something

ValueErrorTraceback (most recent call last)
<ipython-input-255-7df608ebbf8e> in <module>()
      1 for i in range(0 , times):
      2     day = day
----> 3     fulldateadd = datetime.date(year, month, day)
      4     print('today is {0}, do something'.format(fulldateadd))
      5     day = day + 7

ValueError: day is out of range for month

February doesn't have 31 days... so you would have to include a check with a mapping to the number of days in each month.二月没有 31 天......所以你必须包含一个检查,并映射到每个月的天数。 Including logic for leap years.包括闰年的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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