2013-02-28 91 views
3

我在處理日期時發現非常有用的datetime.datetime對象,但是現在有情況,現在datime.datetime不適用於我。在程序執行期間,日期字段動態計算和這裏的問題:datetime.datetime - 日期字段超出範圍

>>> 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,月沒有29日,但將是巨大的,如果日期時間能明白這一點,並返回該對象

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

什麼是最好的方式解決這種情況?所以,我在尋找一個通用的解決方案,當天參數大於月可能有的天數時。

+5

不,這將*不*很大。顯式比隱式更好。 – 2013-02-28 11:31:12

+0

您實際上無法獲得修復損壞的邏輯的一般解決方案。你可以嘗試使用'導入日曆; calendar.monthrange(year,month)'獲取月份日期。 – dmg 2013-02-28 11:36:51

回答

3

雖然有很多可說的對在這種情況下使用try...except,如果你真的只需要一個月+ daysOffset你可以這樣做:

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

基本上,設置月份的一天爲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) 
+0

對我而言,謝謝。 – Zed 2013-02-28 11:44:53

6

來自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) 
1

用下個月的第一天,然後減去一天避免使用日曆

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