当前位置: 首页 > news >正文

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 Truereturn False# 获取月份对应的天数def init(self, year):if self.check(year): # 瑞年self.mp[2] = 29   # 根据年月日获取对应的天数def getDays(self, year, month, day):cnt = 0for m in range(1, month):cnt += self.mp[m]cnt += dayreturn cnt# 根据某年的天数获取年月日def getDate(self, year, days):cnt, month = 0, 1for i in range(1, 13):month = iif 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----------------------##

相关文章:

  • Vue基础(18)_收集表单数据
  • 06-three.js 创建自己的缓冲几何体
  • 【数据结构】map/set模拟实现(红黑树作底层)
  • 道路交通标志检测数据集-智能地图与导航 交通监控与执法 智慧城市交通管理-2,000 张图像
  • cocos creator 3.8 - 精品源码 - 六边形消消乐(六边形叠叠乐、六边形堆叠战士)
  • 【安全建设 | 从0到1】企业安全体系建设线路
  • OpenCV图像噪点消除五大滤波方法
  • spring-ai 1.0.0 (2)提示词,消息构建和移植能力
  • python学习打卡day57
  • JWT认证性能优化实战指南
  • 【数据结构】AVL树和红黑树的Insert(插入)(实现map.insert)
  • BUUCTF [ACTF新生赛2020]music 1
  • 如何提取mdd字典中音频文件并转化为mp3
  • Rust代码规范之蛇形命名法和驼峰命名法
  • C++共享型智能指针std::shared_ptr使用介绍
  • Webpack 核心与基础使用
  • NLog、log4net、Serilog 和 Microsoft.Extensions.Logging 四大 .NET 日志库的综合对比
  • 学习使用dotnet-dump工具分析.net内存转储文件(2)
  • OpenLayers 下载地图切片
  • Python 中定义和调用函数:基础与进阶指南