python计算活了多少天_python 计算活的天数

Code# By Websten from forums

#

# Given your birthday and the current date, calculate your age in days.

# Compensate for leap days.

# Assume that the birthday and current date are correct dates (and no time travel).

# Simply put, if you were born 1 Jan 2012 and todays date is 2 Jan 2012

# you are 1 day old.

#

# Hint

# A whole year is 365 days, 366 if a leap year.

def isLeap(year):

if year%400==0:

return True

if year%4==0 and year%100!=0:

return True

return False

def nextDay(year, month, day):

"""Simple version: assume every month has 30 days"""

if isLeap(year):

years=[31,29,31,30,31,30,31,31,30,31,30,31]

else:

years=[31,28,31,30,31,30,31,31,30,31,30,31]

if day < years[month-1]:

return year, month, day + 1

else:

if month == 12:

return year + 1, 1, 1

else:

return year, month + 1, 1

def dateIsAfter(year1, month1, day1, year2, month2, day2):

"""Returns True if year1-month1-day1 is after year2-month2-day2. Otherwise, returns False."""

if year1 > year2:

return True

if year1 == year2:

if month1 > month2:

return True

if month1 == month2:

return day1 > day2

return False

def daysBetweenDates(year1, month1, day1, year2, month2, day2):

"""Returns the number of days between year1/month1/day1

and year2/month2/day2. Assumes inputs are valid dates

in Gregorian calendar."""

# program defensively! Add an assertion if the input is not valid!

if dateIsAfter(year2, month2, day2, year1, month1, day1)==False:

return "AssertionError"

days = 0

while dateIsAfter(year2, month2, day2, year1, month1, day1):

days += 1

(year1, month1, day1) = nextDay(year1, month1, day1)

return days

def test():

test_cases = [((2012,1,1,2012,2,28), 58),

((2012,1,1,2012,3,1), 60),

((2011,6,30,2012,6,30), 366),

((2011,1,1,2012,8,8), 585 ),

((1900,1,1,1999,12,31), 36523)]

for (args, answer) in test_cases:

result = daysBetweenDates(*args)

if result != answer:

print "Test with data:", args, "failed"

else:

print "Test case passed!"

test()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值