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

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----------------------##
http://www.xdnf.cn/news/14679.html

相关文章:

  • 量化面试绿皮书:56. 多项式求和
  • web3 docs
  • Linux进程关系
  • Flutter 网络请求指南, 从 iOS 到 Flutter 的 Dio + Retrofit 组合
  • 飞算科技依托 JavaAI 核心技术,打造企业级智能开发全场景方案
  • 数据应该如何组织,才能让Excel“读懂”?
  • Django ORM 1. 创建模型(Model)
  • 【2024 CVPR-Backbone】RepViT: Revisiting Mobile CNN From ViT Perspective
  • 什么是上证50etf期权波动率?
  • CPT204-Advanced OO Programming: Lists, Stacks, Queues, and Priority Queues
  • 工作台-02.代码开发
  • HTTP协议中Connection: Keep-Alive和Keep-Alive: timeout=60, max=100的作用
  • 什么是国际期货?期货交易平台搭建
  • [ linux-系统 ] 磁盘与文件系统
  • 【大模型实战 | BERT 量化分析(2)】
  • 从萌芽到领航:广州华锐互动的 AR 奋进之路​
  • 【github】从本地更新仓库里的文件笔记
  • MCP-安全(代码实例)
  • oracle基础审计管理
  • 【Linux指南】压缩、网络传输与系统工具
  • 2025.6.26总结
  • Kotlin环境搭建与基础语法入门
  • springcloud 尚硅谷 看到9开头
  • linux cp与mv那个更可靠
  • MySQL5.7和8.0 破解root密码
  • mysql之timestamp字段自动更新问题
  • ISP Pipeline(5): Auto White Balance Gain Control (AWB) 自动白平衡
  • 教程 | 一键批量下载 Dify「Markdown 转 Docx」生成的 Word 文件(附源码)
  • 【AI News | 20250626】每日AI进展
  • 兰洋科技上合组织论坛发表专题分享,全球液冷布局引领绿色算力未来