一、閏年的定義
閏年是指公曆年份為4的倍數的年份為閏年,但是整百的年份要被400整除才是閏年
例如1900年就不是閏年,但是2000年是閏年
使用Python可以很容易的判斷某一年份是否為閏年,具體代碼如下:
def is_leap_year(year): '''判斷某一年是否為閏年''' return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 if is_leap_year(2000): print('2000年是閏年') else: print('2000年不是閏年')
二、判斷某個範圍內的閏年數量
對於一個給定的年份區間,可以通過遍歷每一年來判斷其中閏年的數量,具體代碼如下:
def count_leap_years(start, end): '''計算從 start 到 end 之間閏年的數量''' count = 0 for year in range(start, end+1): if is_leap_year(year): count += 1 return count print(f'1900年到2019年之間一共有{count_leap_years(1900,2019)}個閏年')
三、指定日期為該年的第幾天
給定一個日期,可以通過計算該日期距離該年1月1日的天數來得到該日期在該年中的第幾天
具體代碼如下:
def day_of_year(year, month, day): '''返回給定日期在該年中的第幾天''' days_per_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if is_leap_year(year): days_per_month[2] = 29 total_days = day for i in range(1, month): total_days += days_per_month[i] return total_days print(day_of_year(2022, 6, 15))
四、日期之間的間隔天數
給定兩個日期,可以通過計算兩個日期距離其所在年份1月1日的天數之差來計算它們之間的間隔天數
具體代碼如下:
def days_between_dates(date1, date2): '''返回給定兩個日期之間相差的天數''' year1, month1, day1 = date1 year2, month2, day2 = date2 days1 = day_of_year(year1, month1, day1) days2 = day_of_year(year2, month2, day2) if year1 == year2: return abs(days2 - days1) elif year2 - year1 == 1 and month1 > month2: return days_between_dates((year1+1, 1, 1), (year2, month2, day2)) + 365 - days1 else: days_in_between_years = 0 for year in range(year1+1, year2): if is_leap_year(year): days_in_between_years += 366 else: days_in_between_years += 365 return days_in_between_years + days_between_dates((year1, 12, 31), (year1, 12, 31)) + days_between_dates((year2, 1, 1), (year2, month2, day2)) print(days_between_dates((2020, 5, 28), (2022, 6, 15)))
五、其他
Python中datetime模塊提供了很多方便的時間處理工具,在處理日期和時間方面也提供很多便利
例如在datetime模塊中,可以通過today()方法獲得當前日期,通過strftime()方法將日期格式化為字元串
具體代碼如下:
import datetime today = datetime.datetime.today() print(today.strftime('%Y-%m-%d'))
此外,還有一些其他的工具可以方便地處理日期和時間,例如arrow和pendulum等庫
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/182956.html