閏年か判定するには、calendar モジュールの isleap を使用します。
うるう年の判定方法
import calendar
結果(True or False) = calendar.isleap(調べたい年)
- 閏年なら True を、そうでなければ False を返します。
- calendar は標準モジュールのため、別途インストールは不要です。
- 調べたい年 は、数値型で渡します。
注意点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('今年は閏年ではありません。')
うるう年の条件(グレゴリオ暦の場合)
- 年号が400で割り切れる年は閏年
- 年号が100で割り切れず、年号が4で割り切れる年は閏年
年齢計算
日本の法律では誕生日が2月29日の場合、平年、うるう年を問わず、2月28日24時に加齢します。資料
サンプルコードのダウンロード
サンプルコードの実行には Python3 以上のバージョンが必要です。検証環境
- Microsoft Windows 10 Pro Version 1909 OS Build 18363.657
- Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32