本文實例講述了Python編程實現輸入某年某月某日計算出這一天是該年第幾天的方法。分享給大家供大家參考,具體如下:
#基于 Python3
一種做法:
def is_leap_year(year): # 判斷閏年,是則返回True,否則返回False if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return Falsedef function1(year, month, day): # 計算給定日期是那一年的第幾天 leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] no_leap_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap_year(year): result = sum(leap_year[:month - 1]) + day else: result = sum(no_leap_year[:month - 1]) + day return result
但是如果是你自己遇到了這樣的需求,那么就沒必要這么復雜了。因為Python內置了完善的時間和日期處理函數。
import datetimeimport timedef function2(year, month, day): # 直接使用Python內置模塊datetime的格式轉換功能得到結果 date = datetime.date(year, month, day) return date.strftime('%j')
需要注意的是,上面的寫法里函數的參數分別是年月日的整數,如果你想傳入字符串,比如"2016-10-1",那就需要先對字符串做處理了。
同樣的,也可以自己做或者用內置函數。
# 假如輸入格式為字符串(比如從命令行讀入字符串2016-10-1),則需要先對輸入內容進行處理_input = '2016-10-1'_year1 = int(_input.split('-')[0])_month1 = int(_input.split('-')[1])_day1 = int(_input.split('-')[2])# 當然你也可以用datetime的內置方法進行格式處理t = time.strptime(_input, '%Y-%m-%d')_year2 = t.tm_year_month2 = t.tm_mon_day2 = t.tm_mday
下面是完整的代碼,測試"2016-10-1"的結果均為275。
import datetimeimport timedef is_leap_year(year): # 判斷閏年,是則返回True,否則返回False if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: return True else: return Falsedef function1(year, month, day): # 計算給定日期是那一年的第幾天 leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] no_leap_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap_year(year): result = sum(leap_year[:month - 1]) + day else: result = sum(no_leap_year[:month - 1]) + day return resultdef function2(year, month, day): # 直接使用Python內置模塊datetime的格式轉換功能得到結果 date = datetime.date(year, month, day) return date.strftime('%j')print(function1(2016, 10, 1))print(function2(2016, 10, 1))# 假如輸入格式為字符串(比如從命令行讀入字符串2016-10-1),則需要先對輸入內容進行處理_input = '2016-10-1'_split = _input.split('-')_year1 = int(_split[0])_month1 = int(_split[1])_day1 = int(_split[2])print(function1(_year1, _month1, _day1))print(function2(_year1, _month1, _day1))# 當然你也可以用datetime的內置方法進行格式處理t = time.strptime(_input, '%Y-%m-%d')_year2 = t.tm_year_month2 = t.tm_mon_day2 = t.tm_mdayprint(function1(_year2, _month2, _day2))print(function2(_year2, _month2, _day2))
新聞熱點
疑難解答