我在处理日期时发现了非常有用的datetime.datetime对象,但是现在我的情况是datime.datetime对我不起作用.在执行程序时,day字段是动态计算的,这就是问题所在:
>>> datetime.datetime(2013, 2, 29, 10, 15)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: day is out of range for month
Run Code Online (Sandbox Code Playgroud)
好的,二月没有29天,但如果日期时间可以解决并返回此对象,那将会很棒
datetime.datetime(2013, 3, 1, 10, 15)
Run Code Online (Sandbox Code Playgroud)
解决这种情况的最佳方法是什么?所以,我正在寻找一个通用的解决方案,当天参数大于一个月的天数.
从Python的禅宗:明确比隐含更好.当您尝试创建无效日期等错误时,您需要明确处理该情况.
如何处理该异常完全取决于您的应用程序.您可以通知最终用户该错误,或者您可以尝试将日期转移到下个月,或将当天限制在当月的最后一个法定日期.根据您的使用情况,所有这些都是有效的选项.
以下代码会将"剩余"天数转移到下个月.所以2013-02-30将成为2013-03-02.
import calendar
import datetime
try:
dt = datetime.datetime(year, month, day, hour, minute)
except ValueError:
# Oops, invalid date. Assume we can fix this by shifting this to the next month instead
_, monthdays = calendar.monthrange(year, month)
if monthdays < day:
surplus = day - monthdays
dt = datetime.datetime(year, month, monthdays, hour, minute) + datetime.timedelta(days=surplus)
Run Code Online (Sandbox Code Playgroud)