Python3 - うるう年かを調べる方法

閏年か判定するには、calendar モジュールの isleap を使用します。

うるう年の判定方法

import calendar
結果(True or False) = calendar.isleap(調べたい年)

注意点1 文字列を渡すと例外発生

文字列を渡すと、エラー[TypeError: not all arguments converted during string formatting]が発生するので、数値型にキャストしてから isleap に渡します。

エラーになる例

result = calendar.isleap('2020')
result = calendar.isleap("2020")

回避方法

result = calendar.isleap(int('2020'))
result = calendar.isleap(int("2020"))

注意点2 マイナス値を渡しても True が返る

次の結果は、どちらも True が返されます。
result = calendar.isleap('2020')
result = calendar.isleap('-2020')

サンプルコード

今年がうるう年か調べます。
import datetime
import calendar

nowYear = datetime.date.today().year
if calendar.isleap(nowYear):
    print('今年は閏年です。')
else:
    print('今年は閏年ではありません。')

うるう年の条件(グレゴリオ暦の場合)

年齢計算

日本の法律では誕生日が2月29日の場合、平年、うるう年を問わず、2月28日24時に加齢します。

資料

サンプルコードのダウンロード

サンプルコードの実行には Python3 以上のバージョンが必要です。

検証環境

関連ページ