开发者

python实现日期与天数的转换

目录
  • 闰年判断
  • 每个月的对应的天数

闰年判断

  • 一个年份是闰年当且仅当它满足下列两种情况其中的一种:
    • 这个年份是4 的整数倍,但不是100 的整数倍;
    • 这个年份是 400 的整数倍。

每个月的对应的天数

  • 每年12 个月份,其中1,3,5,7,8,10,12,每个月有 31 天;
  • 4,6,9,11月每个月有 30 天;
  • 对于 2 月,闰年有 29 天,平年有 28 天。
import sys

# 日期处理-日期转换为天数,根据某年过去的天数获取具体的日期
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 yeaandroidr % 100 != 0):
            return Thttp://www.devze.comrue
        return False
    # 获取月份对应的天数
    def init(self, year):
        ihttp://www.devze.comf self.check(year): # 瑞年
            self.mp[2] = 29   
    # 根据年月日获取对应的天数
    def getDays(self, year, month, day):
        cnt = 0
        for m in range(1, month):
            cnt += self.mp[m]
        cnt += day
        return cnt
    # 根据某年的天数获取年月日
    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)
prjsint('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: javascript6 , days is 157
# 	year is 2025, days is 157, conver to date is 2025 6 6
##------------------------over----------------------##

到此这篇关于python实现日期与天数的转换的文章就介绍到这了,更多相关python 日期与天数转换内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜