python函数判断闰年/天数等

练习一:

写一个判断闰年的函数,参数为年、月、日。若是是闰年,返回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)

猜你喜欢

转载自www.cnblogs.com/shengyin/p/11235626.html