1. 程式人生 > >練習一百例之4--日期計算

練習一百例之4--日期計算

習題 異常 like 答案 lease ret time com date

問題及答案實例四,關於日期的簡單練習
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--日期計算