Leap year / python function to determine the number of days

Exercise 1:

Write a judgment leap year function, the parameters for the year, month and day. If it is a leap year, returns True.

 

The most succinct wording currently found, like this to be realized.

1 #判断闰年
2 def is_leap_year(year):
3     return  (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

 

Extended look, judgment is the first few days of the year.

 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))

 

Of course, python datetime module comes, we can achieve more than a way to go.

. 1  Import datetime         # introduced datetime module 
2  DEF getDayInYear (year, month The, Day):
 . 3      DATE = datetime.date (year, month The, Day)
 . 4      return date.strftime ( ' % J ' )               # Returns the first few day of the year day, range [001,366] 
. 5      
. 6  Print (getDayInYear (2008,1,1 ))
 . 7  Print (getDayInYear (2008,10,1 ))
 . 8  Print (getDayInYear (2009,10,1))

 

Exercise Two:

There is a file named output_1981.10.21.txt.

Use the following Python: read the date and time information in the file name, and find out which is the week day.

The file renamed output_YYYY-MM-DD-W.txt (YYYY: four year, MM: month of two, DD: day two's, W: week of the week, and assuming that the first day of a week Monday )

 

Using regular and time functions to achieve.

. 1  Import Re, datetime
 2 m = the re.search ( ' Output _ (? P <year> \. 4 {D}). (? P <month The> \ D {2}). (? P <Day> \ D {2 }) ' , ' output_1981.10.21.txt ' )
 . 3  # acquires the week, a written 
. 4  DEF getdayinyear (year, month The, Day):
 . 5      DATE = datetime.date (year, month The, Day)
 . 6      return date.strftime ( ' % W ' )
 . 7 W is = getdayinyear (1981,10,21)                   # this formulation is suitable for multiple days 
. 8  
. 9  # acquired week, writing two 
10 W is A datetime.datetime = (int (m.group (' Year ' )), int (m.group ( ' month The ' )), int (m.group ( ' Day ' ))). The strftime ( " % W " )     # single date wording 
. 11  
12 is  # Reference 
13 >> > from datetime Import datetime
 14 >>> Print datetime (1981,10,21) .strftime ( " % W " )     # writing a single date 
15  
16 filename = ' output_ ' + m.group ( 'year') + ' - ' + m.group ( ' month The ' ) + ' - ' + m.group ( ' Day ' ) + ' - ' + + W is ' .txt ' 
. 17  # by rename the method may attempt to write 
18 is  
. 19  Print (W is)
 20 is  Print (filename)

 

Guess you like

Origin www.cnblogs.com/shengyin/p/11235626.html