HOWTO · Python

Python Timedelta Months を使用して日付を計算する

この記事では、Python で現在の日付から 6 か月後の日付を計算する方法について説明します。

このページの内容

このガイドでは、Python で timedelta を使用して datetime を使用する方法を学習します。 現在の日付またはその他の日付から 6 か月後の日付を計算する方法を見ていきます。

飛び込みましょう!

Python datetime 関数

まず、datetime 関数の仕組みと、機能を制限する欠点を見ていきます。 最初に知っておくべきことは、コードに datetime をインポートすることです。

import datetime

その後、datetime のインスタンスを作成します。 インスタンスを作成したら、その算術関数を使用できます。

日と月を差し引くことができます。 次のコードを見てください。

# instance of datetime
date = datetime.datetime(2022, 2, 1)
# subtracting 1 from the month
date = date.replace(month=date.month - 1)
print(date)

出力:

2022-01-01 00:00:00

上記のコードでわかるように、算術関数を使用して、以前に設定した日付から 1 か月を減算しています。 しかし、ここで落とし穴があります。上記の結果から 1 か月を差し引こうとするとどうなるでしょうか。

コードはエラーになります。 見てください。

date = date.replace(month=date.month - 1)

出力:

    date = date.replace(month=date.month-1)
ValueError: month must be in 1..12

datetime 関数では、サポートされていないため、算術関数を使用して年全体を減算することはできません。 同様に、現在の日付が 12 月の最後の日にあるときに 1 または 2 を追加すると、同じエラーが発生します。

# if you add 1 in date, it will throw an error because it doesn't support it
date = datetime.datetime(2022, 12, 1)
date_ = date.replace(month=date_1.month + 1)

出力:

    date = date.replace(month=date.month+1)
ValueError: month must be in 1..12

では、質問に戻りますが、現在の日付またはその他の日付から 6 か月後の日付を計算するにはどうすればよいでしょうか。 答えは、relativedelta を使用することにあります。

relativedelta() を使用して Python を使用して日付を計算する

Python コードで relativedelta を使用する前に、dateutil をインストールして relativedelta をインポートする必要があります。 コマンド プロンプトで次のコマンドを実行して、dateutil をインストールします。

pip install python-dateutil

インストールしたら、そこから relativedelta をインポートする必要があります。

from dateutil import relativedelta

その後、現在の問題を解決するために datetime と relativedelta の両方を使用する必要があります。 次のコードを見てください。

date = datetime.datetime(2022, 1, 1)
# created the instance of the datetime and set the current date as 2022,1,1

次に、relativedelta のインスタンスを作成し、月の値を 1 に設定します。

r_date = relativedelta.relativedelta(months=1)

あとは、datetime のインスタンスから relativedelta のインスタンスを差し引くだけです。 それは私たちの望む答えを与えてくれます。

# if you subtract the relativedelta variable with the date instance, it will work correctly and change the year too.
new_date = date - r_date
print(new_date)

出力:

2021-12-01 00:00:00

同様に、日付に 1 を追加すると、目的の出力が得られます。

これで、この手法を使用して、現在の日付から任意の日付を計算できます。 これは、現在の日付から 6 か月後の日付を計算する方法の答えです。