0
0

More than 1 year has passed since last update.

【Python】与えられた月と年を基に、築年月を求めるコードを実装

Posted at

概要

Pythonで、与えられた月と年を基に、現在の日付との差を計算して築年月を求めるコードを実装しました。その際、細かな注意点があることも記載します。

サンプルコード

以下に二つの関数を記載しました。
どちらも築年月を抽出するコードです。

from datetime import datetime

# 関数1
def calculate_age_month_1(month, year):
    start_date = datetime(int(year), int(month), 1)
    end_date = datetime.now()
    duration = end_date - start_date
    years = duration.days // 365
    months = (duration.days % 365) // 30

    return '' + str(years) + '' + str(months) + 'ヶ月'

chikunengestu = calculate_age_month_1(9, 1936)
print(chikunengestu)

# 関数2
def calculate_age_month_2(month, year):
    current_date = datetime.now()
    input_date = datetime(year, month, 1)
    years = current_date.year - input_date.year
    months = current_date.month - input_date.month
    
    if months < 0:
        years -= 1
        months = 12 + months
    
    return '' + str(years) + '' + str(months) + 'ヶ月'

chikunengestu = calculate_age_month_2(9, 1936)
print(chikunengestu)

しかし、実はこのコード、結果は以下のとおりです。

築86年12ヶ月
築86年11ヶ月

なぜ1ヶ月のずれがあるのでしょうか?

それは、関数1の方では「1年を365日、1ヶ月を30日」と仮定しており、日数を30日で割ることによって月数を計算しようとしている点にあります。月数を日数で単純に割ると、30日未満やの月や31日ある月もすべて1ヶ月として計算され、計算結果がずれてしまうのです(正確な月数を考慮していない)。

ちなみに2023年8月現在から計算すると1936年9月ではズレが発生することが確認できました。1936年8月を渡してあげると、どちらの関数でも築87年0ヶ月という結果になりました。

ということで、正確に築年月を抽出する場合は関数2の方を使いましょう。

ちなみに、datetime(year, month, 1)の中の1は、指定した年と月に対して、1日目を表しています。これにより、指定された年と月の最初の日を表すdatetimeオブジェクトが生成されます。

TypeError: 'module' object is not callableエラー

import文でimport datetimeとだけ書くと、以下のエラーになります。

TypeError: 'module' object is not callable

これは、datetimeモジュールにはdatetime以外にもdatetimeなどのオブジェクトがあり、datetimeモジュールのdatetimeオブジェクトを指定してあげる必要があるためです。

参考:【Python】「TypeError: ‘module’ object is not callable」の対処法

0
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
0
0