# -*- coding: UTF-8 -*- import time def What_day_of_the_year(inputTime): #函數,判斷字符串是否爲數字 def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False #判斷字符串是否含有「-」分割符(是否按格式輸入) if inputTime.find('-') != -1: #if '' in inputTime != 'False' or ' ' in inputTime != 'False': #想判斷是否含空格(含空格不符合格式),效果不佳,已廢棄;改用Python異常處理 timeList = inputTime.split('-') #以「-」符分割字符串,賦值爲列表 #經過for循環+自定義的is_number函數判斷列表是否含有字母(含有字母不符合格式) trueList = [] for numberValue in timeList: trueList.append(is_number(numberValue)) if trueList.count('False') == 0: timeList = list(map(int, timeList)) #將列表從字符串轉換爲int整數 if timeList[0] % 4 == 0 or timeList[0] % 400 == 0: #判斷是否爲閏年。 timeTotal = (7 * 31) + (4 * 30) + 29 exceptSameMonthDay = 0 for monthValue in range(1,timeList[1]): #計算除當月在內的,已過天數;如:2009-11-14,不算第11月。僅算1~10月 if monthValue == 1 or monthValue == 3 or monthValue == 5 or monthValue == 7 or monthValue == 8 or monthValue == 10 or monthValue == 12: exceptSameMonthDay += 31 elif monthValue == 4 or monthValue == 6 or monthValue == 9 or monthValue == 11: exceptSameMonthDay += 30 elif monthValue == 2: exceptSameMonthDay += 29 return exceptSameMonthDay + timeList[2] else: timeTotal = (7 * 31) + (4 * 30) + 28 exceptSameMonthDay = 0 for monthValue in range(1,timeList[1]): if monthValue == 1 or monthValue == 3 or monthValue == 5 or monthValue == 7 or monthValue == 8 or monthValue == 10 or monthValue == 12: exceptSameMonthDay += 31 elif monthValue == 4 or monthValue == 6 or monthValue == 9 or monthValue == 11: exceptSameMonthDay += 30 elif monthValue == 2: exceptSameMonthDay += 28 return exceptSameMonthDay + timeList[2] else: return 1 #else: #return 1 else: return 1 timeValue = time.strftime("%Y-%m-%d", time.localtime()) #獲取當前日期,並格式化 # 格式化成2020-02-26形式 tipsValue = '請輸入日期,如:' + timeValue + ':' inputTime = input(tipsValue) try: inputTime = What_day_of_the_year(inputTime) if inputTime == 1: print('您的輸入有誤!') else: print(inputTime) except : print('您的輸入有誤!')
如把 return exceptSameMonthDay + timeList[2] 改成 return timeTotal - (exceptSameMonthDay + timeList[2]) 還能夠計算剩餘天數。app