python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python 日期与天数转换

python实现日期与天数的转换

作者:忆杰

本文主要介绍了python实现日期与天数的转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

闰年判断

每个月的对应的天数

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 year % 100 != 0):
            return True
        return False
    # 获取月份对应的天数
    def init(self, year):
        if 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)
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----------------------##

到此这篇关于python实现日期与天数的转换的文章就介绍到这了,更多相关python 日期与天数转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文