【Python】计算一年内的总天数(还有跨年日期)

花了一段时间才找到Python中求一年中总日数(total day of the Year)的格式代码,所以也把计算方法记录下来。

基本

首先,简单地找出一年中的总天数,

strftime() 和 strptime() 的格式代码是 %j

↓看这里
使用 strftime(‘%j’) 进行转换会返回用零填充的 3 位总天数。
然后可以用int()来转为数值。

import datetime

def calc():

    day = datetime.date(2023, 4, 1)
    total_day = day.strftime('%j')

    print(f'2023/04/01的总天数 = {
      
      total_day}')

    total_int = int(total_day)
    print(f'用 int 处理 : {
      
      total_int}')

if __name__ == '__main__':
    calc()
$ python test1.py
2023/04/01的总天数 = 091int 处理 : 91

闰年

改一下年份,看看闰年的总天数。

import datetime

def calc():

    day = datetime.date(2020, 4, 1)
    total_day = day.strftime('%j')

    print(f'2020/04/01的总天数 = {
      
      total_day}')

if __name__ == '__main__':
    calc()
$ python test2.py
2020/04/01的总天数 = 092

2023/04/01 的总天数为 91 天,因此可以看到闰年中的 2/29 也已正确添加。

处理跨年的总天数

对于那些在年份中使用 366 (367) ,或更大的值,或在处理从年底到年初的总天数时,将上一年年底的值设为负数,将明年一月的值设置为 366 或更高的情况

基本上,只需要在下一年的总天数上加上365,但是需要考虑到上一年是否是闰年,所以需要加上上一年12月31日的总天数(365或 366)。

import datetime

def calc(year):

    next_year = year + 1  # 定义明年

    day = datetime.date(year, 12, 1)  # 前年12/1
    additional_day = datetime.date(year, 12, 31)  # 追加的12/31
    spanning_year = datetime.date(next_year, 1, 3)  # 想要跨年计算的天数

    total_day = day.strftime('%j')
    additional_total_day = int(additional_day.strftime('%j'))
    next_year_total_day = int(spanning_year.strftime('%j'))
    sppaning_total_day = additional_total_day + next_year_total_day

    print(f'{
      
      year}/12/01的总天数 = {
      
      total_day}')
    print(f'{
      
      year}/12/31的总天数 = {
      
      additional_total_day}')
    print(f'{
      
      next_year}/01/03的总天数 = {
      
      sppaning_total_day}')

if __name__ == '__main__':
    print('======== 平年 ========')
    calc(2022)
    print('====== 闰年考虑 ======')
    calc(2020)
$ python test_spanning_year1.py
======== 平年 ========
2022/12/01的总天数 = 335
2022/12/31的总天数 = 365
2023/01/03的总天数 = 368
====== 闰年考虑 ======
2020/12/01的总天数 = 336
2020/12/31的总天数 = 366
2021/01/03的总天数 = 369

可以看到已经考虑了 2020 年的闰年,并添加了额外的一天。

让上一年的 12 月成为负值

最后的计算有点复杂。
首先,由于它可以取负值,需要决定在哪里放置零。
如果忽略零并且不关心 1/1 是否是第一天,上一年的 12/31 是否是 -1 天,那很好,但是当编写时,1 天的差异看起来像差了2天。我认为可能会出现一些不便。

这次我想用负数来表达过去的一年,所以
・上年的12月31日为-1日。
・1/1 是第 0 天
・1 月 1 日之后的总天数为(正常总天数 - 1)天。
按这样来计算.

如果要将上一年表示为负数,基本上可以用(总天数 - 365 - 1)来表示,但与上一节中的+365示例一样,需要考虑到以下情况:上年为闰年,计算公式为(总天数- 上年 12/31 总天数 - 1)。

$ python test_spanning_year2.py
======== 平年 ========
2023/01/05的总天数 = 4
2022/12/31的总天数 = 365
2022/12/27的总天数 = -5
====== 闰年考慮 ======
2021/01/05的总天数 = 4
2020/12/31的总天数 = 366
2020/12/27的总天数 = -5

很难判断结果是否正确,所以制作一个假设值表格并检查。
在这两个年份中,1/1 应为 0,12/31 应为 -1,因此正确的总日期如下表所示。在这里插入图片描述与计算结果相符!

猜你喜欢

转载自blog.csdn.net/Allan_lam/article/details/134994387