python实现日期与天数的转换 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 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, 6d = 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 日期与天数转换内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
无论兄弟们可能感兴趣的文章:
- 在?Python?中怎样将天数添加到日期
- Python+SeaTable实现计算两个日期间的职业日天数
- python将天数转换为日期字符串的技巧实例
- Python 3.3实现计算两个日期间隔秒数/天数的技巧示例
- Python计算两个日期相差天数的技巧示例