練習一:
寫一個判斷閏年的函數,參數為年、月、日。若是是閏年,返回True。
目前找到的最簡潔的寫法,很好用。
1 #判斷閏年 2 def is_leap_year(year): 3 return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
引申一下,判斷是這一年的第幾天。
1 #判斷是這一年的第幾天 2 def getDayInYear(year,month,day): 3 month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 4 if is_leap_year(year): 5 month_day[1]=29 6 return sum(month_day[:month - 1]) + day 7 8 print(getDayInYear(2008,1,1)) 9 print(getDayInYear(2008,10,1)) 10 print(getDayInYear(2009,10,1))
當然,python自帶datetime模塊,我們可以多一種方法去實現。
1 import datetime #導入datetime模塊 2 def getDayInYear(year, month, day): 3 date = datetime.date(year, month, day) 4 return date.strftime('%j') #返回當天是當年的第幾天,范圍[001,366] 5 6 print(getDayInYear(2008,1,1)) 7 print(getDayInYear(2008,10,1)) 8 print(getDayInYear(2009,10,1))
練習二:
有一個文件,文件名為output_1981.10.21.txt 。
下面使用Python:讀取文件名中的日期時間信息,並找出這一天是周幾。
將文件改名為output_YYYY-MM-DD-W.txt (YYYY:四位的年,MM:兩位的月份,DD:兩位的日,W:一周的周幾,並假設周一為一周第一天)
使用正則和時間函數實現。
1 import re,datetime 2 m = re.search('output_(?P<year>\d{4}).(?P<month>\d{2}).(?P<day>\d{2})','output_1981.10.21.txt') 3 #獲取周幾,寫法一 4 def getdayinyear(year,month,day): 5 date = datetime.date(year,month,day) 6 return date.strftime('%w') 7 W = getdayinyear(1981,10,21) #這種寫法適用於多個日期 8 9 #獲取周幾,寫法二 10 W = datetime.datetime(int(m.group('year')),int(m.group('month')),int(m.group('day'))).strftime("%w") #單個日期的寫法 11 12 #參考 13 >>> from datetime import datetime 14 >>> print datetime(1981,10,21).strftime("%w") #單個日期的寫法 15 16 filename = 'output_' + m.group('year') + '-' + m.group('month') + '-' + m.group('day') + '-' + W + '.txt' 17 #可以嘗試下用rename方法去寫 18 19 print (W) 20 print (filename)
