python實現(xiàn)日期與天數(shù)的轉(zhuǎn)換
更新時間:2025年06月29日 10:36:41 作者:憶杰
本文主要介紹了python實現(xiàn)日期與天數(shù)的轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
閏年判斷
- 一個年份是閏年當(dāng)且僅當(dāng)它滿足下列兩種情況其中的一種:
- 這個年份是4 的整數(shù)倍,但不是100 的整數(shù)倍;
- 這個年份是 400 的整數(shù)倍。
每個月的對應(yīng)的天數(shù)
- 每年12 個月份,其中1,3,5,7,8,10,12,每個月有 31 天;
- 4,6,9,11月每個月有 30 天;
- 對于 2 月,閏年有 29 天,平年有 28 天。
import sys
# 日期處理-日期轉(zhuǎn)換為天數(shù),根據(jù)某年過去的天數(shù)獲取具體的日期
class DateHandle:
def __init__(self) -> None:
self.mp = {1:31, 3:31, 5:31, 7:31, 8:31, 10:31, 12:31, 4:30, 6:30, 9:30, 11:30, 2:28}
# 閏年判斷
def check(self, year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return True
return False
# 獲取月份對應(yīng)的天數(shù)
def init(self, year):
if self.check(year): # 瑞年
self.mp[2] = 29
# 根據(jù)年月日獲取對應(yīng)的天數(shù)
def getDays(self, year, month, day):
cnt = 0
for m in range(1, month):
cnt += self.mp[m]
cnt += day
return cnt
# 根據(jù)某年的天數(shù)獲取年月日
def getDate(self, year, days):
cnt, month = 0, 1
for i in range(1, 13):
month = i
if cnt + self.mp[i] <= days:
cnt += self.mp[i]
else:
break
date = days - cnt
return "%d %d %d" % (year, month, date)
year, month, day = 2025, 6, 6
d = DateHandle()
d.init(year)
cnt = d.getDays(year, month, day)
date = d.getDate(year, cnt)
print('year: %d, month: %d, day: %d , days is %d' % (year, month, day, cnt))
print('year is %d, days is %d, conver to date is %s' % (year, cnt, date))
##------------------------output--------------------##
# year: 2025, month: 6, day: 6 , days is 157
# year is 2025, days is 157, conver to date is 2025 6 6
##------------------------over----------------------##到此這篇關(guān)于python實現(xiàn)日期與天數(shù)的轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)python 日期與天數(shù)轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python word文本自動化操作實現(xiàn)方法解析
這篇文章主要介紹了Python word文本自動化操作實現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
python中format函數(shù)與round函數(shù)的區(qū)別
大家好,本篇文章主要講的是python中format函數(shù)與round函數(shù)的區(qū)別,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
python unichr函數(shù)知識點總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于python unichr函數(shù)的知識點總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-12-12
python實現(xiàn)根據(jù)坐標(biāo)將圖片進(jìn)行裁剪
這篇文章主要為大家詳細(xì)介紹了如何使用python實現(xiàn)根據(jù)坐標(biāo)將圖片進(jìn)行裁剪,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-06-06

