简体   繁体   English

日期时间(超出日期的天数)Python

[英]datetime (day out of range) Python

I have a problem with my script. 我的脚本有问题。

end = date(2012, 6, 20)
start = date(2012, 5, 01)
delta = end - start
delta = delta.days
print 'The number of days taken into account for training periods testing:', delta

all_training_periods=[pd.date_range(start=dt.datetime(2012, 5, 01+k),end=dt.datetime(2012, 6,20),freq='10T') for k in range(0,delta)]

The problem is that I have an error message telling me: 问题是我有一条错误消息告诉我:

  File "<ipython-input-192-57c97670a7f1>", line 1, in <module>
    all_training_periods=[pd.date_range(start=dt.datetime(2012, 5, 01+k),end=dt.datetime(2012, 6,20),freq='10T') for k in range(0,delta)]

ValueError: day is out of range for month

The thing here is that I want different training period from the 1st of May to the 20th of June, from the 2nd of May to the 20th of June, ..., from the 19th of June to the 20th of June. 我要的是从5月1日到6月20日,从5月2日到6月20日,...从6月19日到6月20日,不同的培训时间。

我建议像这样增加日期:

datetime.date(2012, 5, 1) + datetime.timedelta(k, 0)

In your code 在你的代码中

end = date(2012, 6, 20)
start = date(2012, 5, 01)
delta = end - start

Where delta.days evaluates 50. Then in your line: 其中delta.days值为50。然后在您的行中:

dt.datetime(2012, 5, 01+k)

will end up with something like: 最终将类似于:

dt.datetime(2012, 5, 01+49)

Then datetime will throw exception since May do not have 49 days. 然后datetime将抛出异常,因为May可能没有49天。 No month have more than 31 days. 没有一个月超过31天。

Try this: 尝试这个:

from datetime import timedelta
dt.datetime(2012, 5, 01) + timedelta(days=k)

This will make the correct calculation. 这将进行正确的计算。

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

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