ValueError:day超出了date datetime的范围

时间:2017-03-08 14:05:22

标签: python python-3.x datetime

我遇到了一些我写过的代码问题。我接受四个输入(日,月和年)作为日期,以及他们想要重复任务的次数(例如,每周一,持续3周)。代码很棒,但是如果几个月之间的周数不同,我会收到此错误:

  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

相关的部分代码:

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

当天数超过31天时,我试图增加月份,但似乎无效。

1 个答案:

答案 0 :(得分:2)

为什么增加日期时间的组件然后创建新的组件有几个原因不是一个好主意。主要是因为处理公历本身并不是那种令人愉快的恕我直言,日期时间对象可以为你做。

在这方面,一个更简单的方法是在循环中为你的日期时间添加一个timedelta。例如,

>>> 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

根据您的使用情况,这也可以放在发电机中。

>>> 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

或与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')]

现在,如果您尝试使用此方法的示例,会发生什么?

>>> 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

二月没有31天...所以你必须包括一张支票,其中包含每个月天数的映射。包括闰年的逻辑。