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

问题及答案实例四,关于日期的简单练习
Python练习题问题如下:
简述:要求输入某年某月某日
提问:求判断输入日期是当年中的第几天?
###如果用time模块的话,将会更简单!!!

#!/usr/bin/python
# -*- coding: UTF-8 -*-
  
year = int(raw_input('year:
'))
month = int(raw_input('month:
'))
day = int(raw_input('day:
'))
  
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()))
使用time模块

1 import time
2 str = raw_input("输入日期")#str = "20170102"
3 try:
4     struct_time = time.strptime(str,"%Y%m%d")
5     print struct_time.tm_yday
6 except:
7     print "wrong input,like 20170101"

这就说明,如果了解模块更多,问题更简单







原文地址:https://www.cnblogs.com/if-then/p/7105972.html