LoginSignup
1
0

Pythonでの閏年判断

Last updated at Posted at 2024-03-04

閏年で不幸になる人を少しでも減らすためのメモ

閏年の特徴

↓とてもわかりやすいサイト↓
https://www.casio.com/jp/watches/contents/leap-year/

  • 閏年は、西暦年が4で割り切れる年
  • ただし、100で割り切れる年は閏年ではない
  • しかし、400で割り切れる年は閏年になる
    このルールにより、閏年は一般的に4年に1度発生するが、上記の例外によって調整される

検索条件で1年前以降とかを指定する時に何も考えずにyear - 1とかしちゃうと閏年の日にエラーになる(戒め)

指定した年が閏年かどうかを判断

Pythonでは、calendar モジュールの isleap(year) 関数を使用して、指定した年が閏年かどうかを判断できる

is_leap = calendar.isleap(2024)
print(is_leap)  # 出力: True

指定した範囲内の閏年の数を計算

calendar モジュールの leapdays(y1, y2) 関数は、指定した範囲内の閏年の数を返す。ここで、y1 年から y2 年の直前までの間で閏年がいくつあるかを計算する

num_leap_years = calendar.leapdays(2000, 2024)	# 2000~2023が計算範囲
print(num_leap_years)  # 出力: 6

あとはこのライブラリをこねくり回してやりたい処理を書きましょう

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0