2012-02-28 26 views
16

可能重複:
Get Last Day of the Month in Python如何找到天數在當月

我怎樣才能獲得當月的天數?即如果當前月份是「2012年1月」,我應該得到31.如果是「2012年2月」,我應該得到29.

+3

的天數見這個問題:http://stackoverflow.com/questions/42950/get-last-day python – Peter 2012-02-28 11:37:38

+0

@peter不錯我只是看着http://docs.python.org/library/calendar.html,必須通過glazed傳遞'monthrange' – 2012-02-28 11:40:08

+0

'def days_in_month():return 29' – 2012-02-28 11:52:38

回答

28

正如彼得提到的,calendar.monthrange(year, month)返回週日(0-6〜週一至週日)天(28-31)爲yearmonth

>>> import calendar 
>>> print calendar.monthrange(2012,1)[1] 
31 
>>> calendar.monthrange(2012,2)[1] 
29 

編輯:更新答案返回當月

>>> import calendar 
>>> import datetime 
>>> now = datetime.datetime.now() 
>>> print calendar.monthrange(now.year, now.month)[1] 
29 
+0

謝謝!!!!但我不想硬編碼的日期像(2012,1)..我想它是系統日期 – Alchemist777 2012-02-28 11:51:06

+0

更新了答案。 – BioGeek 2012-02-28 11:58:00

+0

謝謝你這麼多。這適用於Windows ..我使用Ubuntu 11.10..and導入日曆產生錯誤「沒有模塊命名日曆」..任何想法?或者有沒有一種替代方法可以在不使用「壓光機」的情況下完成這項工作? – Alchemist777 2012-02-28 12:04:34