python计算某年某月多少天_Python编程实现输入某年某月某日计算出这一天是该年第几天的方法...
本文實例講述了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 False
def 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 datetime
import time
def 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 datetime
import time
def is_leap_year(year): # 判斷閏年,是則返回True,否則返回False
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
def 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
def 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_mday
print(function1(_year2, _month2, _day2))
print(function2(_year2, _month2, _day2))
# 后面發現我為了編函數寫復雜了,如果輸入是字符串其實一句話就好
import time
_input = '2016-10-1'
# 詳見Python日期和字符串格式互相轉換 https://www.jb51.net/article/66019.htm
t = time.strptime(_input, '%Y-%m-%d')
print(time.strftime('%j',t))
PS:這里再為大家推薦幾款關于日期與天數計算的在線工具供大家使用:
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python计算某年某月多少天_Python编程实现输入某年某月某日计算出这一天是该年第几天的方法...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 漳州开车到甘南藏族自治州米拉日巴佛楼阁距
- 下一篇: 红旗车免费流量有多少年