以下是一些常用的日期函数的实现,每个函数开头的注释中说明了函数的作用,问题的出处可以参考《编程珠玑》第三章练习题4
def leapYear(year):
"""
decide whether year is leap year.
for exmaple:
1900, not leap year
2000,leap year
2004,leap year
2005,not leap year
"""
if year%400==0:
return True
elif year%100==0:
return False
elif year%4==0:
return True
else:
return False
def dayInYear(year,month,day):
"""
calculate the given date's postion in the year
careful about the leap year adjustment
"""
baseMonthDay=[31,28,31,30,31,30,31,31,30,31,30,31]
acc=0
if leapYear(year) and month>2:
acc+=1
for i in range(month-1):
acc+=baseMonthDay[i]
acc+=day
return acc
def weekDayInYear(year,month,day):
"""
calculate the week day of the given date
there exist a formula to do this job,you can google it,
the following code implement the formula
note zero stands for Sunday
"""
if month<3:
year=year-1
month=12+month
c=year/100
y=year%100
m=month
d=day
w=y+y/4+c/4-2*c+26*(m+1)/10+d-1
return w%7
def dateDiff(year1,month1,day1,year2,month2,day2):
"""
calculate the difference between two given dates
we assume that the first date is after the second date,
so if assumption no true,we need swap the two date and
remember that the difference is negative.
"""
if year1==year2:
return dayInYear(year1,month1,day1)-dayInYear(year2,month2,day2)
reverse=False
if year1<year2:
tmp=year1
year1=year2
year2=tmp
tmp=month1
month1=month2
month2=tmp
tmp=day1
day1=day2
day2=tmp
reverse=True
acc=0
if leapYear(year2):
acc+=(366-dayInYear(year2,month2,day2))
else:
acc+=(365-dayInYear(year2,month2,day2))
for i in range(year2+1,year1):
if leapYear(i):
acc+=366
else:
acc+=365
acc+=dayInYear(year1,month1,day1)
if reverse:
return -acc
else:
return acc
def monthCalendar(year,month):
"""
print the given month's calendar.
the primary thing need to be done is to find out the
first day's postion in the given month,after that,we
just need to spread our number after that postion
"""
names=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
printFormat="%10s %10s %10s %10s %10s %10s %10s"
weekDay=weekDayInYear(year,month,1)
print printFormat % tuple(names)
baseMonthDay=[31,28,31,30,31,30,31,31,30,31,30,31]
monthDay=baseMonthDay[month-1]
if leapYear(year) and month==2:
monthDay+=1
index=weekDay
initalList=["" for i in range(7)]
for i in range(1,monthDay+1):
initalList[index]=str(i)
index=(index+1)%7
if index==0:
print printFormat % tuple(initalList)
initalList=["" for i in range(7)]
if initalList[0]!="":
print printFormat % tuple(initalList)