0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

datetime.datetimeにdatetime.timedeltaを足し算する

Posted at

結論

datetime.timedelta型の変数に格納された時差分だけ日時を進める・戻したdatetime.datetime型の変数が返ってきます。

解説

以前、datetime.datetime型同士の変数を引き算するとdatetime.timedeltaが返ってくるという記事を投稿しました。

このdatetime.timedeltaですが、datetime.datetime型の変数に足し算することもできます。結果としては想像できる通り、datetime.timedeltaに格納された時差分だけ日時を進める・戻したdatetime.datetime型が返ってきます。

検証コード

import datetime

# 2023/06/01を表すdatetime
dt = datetime.datetime(2023, 6, 1, 0, 0, 0, 0)

# 2023/06/01の6日後
print(f'dt + datetime.timedelta(days = 6)            :{dt + datetime.timedelta(days = 6)}')

# 2023/06/01の6日と12時間後
print(f'dt + datetime.timedelta(days = 6, hours = 12):{dt + datetime.timedelta(days = 6, hours = 12)}')

# 2023/06/01の6日前(負の数で指定できる)
print(f'dt + datetime.timedelta(days = -6)           :{dt + datetime.timedelta(days = -6)}')
dt + datetime.timedelta(days = 6)            :2023-06-07 00:00:00
dt + datetime.timedelta(days = 6, hours = 12):2023-06-07 12:00:00
dt + datetime.timedelta(days = -6)           :2023-05-26 00:00:00

以上です。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?