首页 > 代码库 > 练习一百例之4--日期计算

练习一百例之4--日期计算

问题及答案实例四,关于日期的简单练习
Python练习题问题如下:
简述:要求输入某年某月某日
提问:求判断输入日期是当年中的第几天?

#!/usr/bin/python
# -*- coding: UTF-8 -*-
  
year = int(raw_input(year:\n))
month = int(raw_input(month:\n))
day = int(raw_input(day:\n))
  
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
    sum = months[month - 1]
else:
    print data error
sum += day
 
leap = 0 #www.iplaypy.com
 
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
    leap = 1
if (leap == 1) and (month > 2):
    sum += 1
print it is the %dth day. % sum

上面是参考答案,以下我的练习,加了一些格式校验,当然写成类可能更好看
此题,实验出来range(0)后 面不执行,不会抛出异常
 1 #!/usr/bin/env python
 2 #coding:utf8
 3 import time,datetime
 4 import os
 5 
 6 days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
 7 def ReadDate():
 8     print "Please input a date string like 20170102 or 2017-01-02"
 9     Dateis = raw_input("Date is:")
10     Dateis = Dateis.replace(-,‘‘)  #加工成20170102
11     print Dateis
12     return Dateis
13 
14 def Datesplite(Dateis):  #返回年月日列表
15     print Dateis
16     if len(Dateis) != 8:
17         print Wrong input!
18     else:
19         try:
20             Year = int(Dateis[0:4])
21             Moon = int(Dateis[4:6].lstrip(0))
22             Day = int(Dateis[6:8].lstrip(0))
23         except:
24             print "Format is Wrong!"
25         return [Year,Moon,Day]
26 
27 def Datecount(list_in):
28     print list_in
29     cday = 0
30     if list_in[0] %4 == 0 and list_in[1] > 2:
31         days[1] =days[1]+1
32     for i in range(list_in[1]-1):  #当range(0)时,这个后面不执行
33         print days[i]
34         cday += days[i]
35     cday +=list_in[2]
36     print cday,th
37 
38 ‘‘‘ 一般调用顺序
39 inputdate = ReadDate()
40 splipdate = Datesplite(inputdate)
41 Datecount(splipdate)
42 ‘‘‘
43 
44 Datecount(Datesplite(ReadDate()))

 







练习一百例之4--日期计算