简体   繁体   English

datetime.datetime - 日期字段超出范围

[英]datetime.datetime - day field out of range

I have found very useful datetime.datetime object when dealing with dates, however I have situation now where datime.datetime isn't working for me.During execution of the program, day field is dynamically calculated and here's the problem: 我在处理日期时发现了非常有用的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

OK, February doesn't have 29 days, but would be great if datetime could figure that out and return this object 好的,二月没有29天,但如果日期时间可以解决并返回此对象,那将会很棒

datetime.datetime(2013, 3, 1, 10, 15)

What's the best way to solve this situation ? 解决这种情况的最佳方法是什么? So, I'm looking for a general solution, when day argument is bigger than number of days month could have. 所以,我正在寻找一个通用的解决方案,当天参数大于一个月的天数。

From the Zen of Python: Explicit is better than implicit . 从Python的禅宗: 明确比隐含更好 When you make an error like trying to create an invalid date, you need to explicitly handle that situation. 当您尝试创建无效日期等错误时,您需要明确处理该情况。

How you handle that exception is entirely up to your application. 如何处理该异常完全取决于您的应用程序。 You could inform the end user of the error, or you could try and shift the days into the next month, or cap the day to the last legal day in the current month. 您可以通知最终用户该错误,或​​者您可以尝试将日期转移到下个月,或将当天限制为当月的最后一个法定日期。 All would be valid options, depending on your use cases . 根据您的使用情况 ,所有这些都是有效的选项。

The following code would shift the 'surplus' days into a next month. 以下代码会将“剩余”天数转移到下个月。 So 2013-02-30 would become 2013-03-02 instead. 所以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)

While there is much to be said about using try...except in this situation, if you really only need the month + daysOffset you can do this: 虽然有很多关于使用try...except说法try...except在这种情况下,如果你真的只需要month + daysOffset,你可以这样做:

d = datetime.datetime(targetYear,targetMonth,1,hour,min,sec)
d = d + datetime.timedelta(days=targetDayOfMonth-1)

Basically, set the day of the month to 1, which is always in the month, then add timedelta to return the appropriate date in a current or future month. 基本上,将月中的日期设置为1(始终在月中),然后添加timedelta以返回当前或未来月份中的相应日期。

d = datetime.datetime(2013, 2, 1, 10, 15) # day of the month is 1
# since the target day is the 29th and that is 28 days after the first
# subtract 1 before creating the timedelta.
d = d + datetime.timedelta(days=28) 
print d
# datetime.datetime(2013, 3, 1, 10, 15)

使用下个月的第一天然后减去一天以避免使用日历

datetime.datetime(targetYear, targetMonth+1, 1) + dt.timedelta(days = -1)

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

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