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.

pythonでdatetime.datetime同士を引き算する

Posted at

結論

datetime.timedelta型が返ってきます。型の名前から想像できる通り、引き算した日時の差を表しています。
datetime.timedelta自体が日時に関するメンバ関数をいくつか持っているため差分計算に役に立ちます。

検証コード

import datetime

# 1日と23時間の時間差
dt1 = datetime.datetime(2023, 6, 1, 0, 0, 0, 0)
dt2 = datetime.datetime(2023, 6, 2, 23, 0, 0, 0)

# datetime同士を引き算する
td21 = dt2 - dt1

# 型を調べる
print(f'td1の型  : {type(td21)}')
# datetime.timedeltaをそのまま出力
print(f'td21     : {td21}')
# 何日差かだけを取り出す
print(f'td21.days: {td21.days}')

# 日はまたぐが時間差は24時間以内
dt3 = datetime.datetime(2023, 6, 1, 23, 0, 0, 0)
dt4 = datetime.datetime(2023, 6, 2, 1, 0, 0, 0)

td43 = dt4 - dt3

# datetime.timedeltaをそのまま出力
print(f'td43     : {td43}')
# 日をまたいでいるが時間差が24時間以内のため日は0日差と出力される
print(f'td43.days: {td43.days}')
td1の型  : <class 'datetime.timedelta'>
td21     : 1 day, 23:00:00
td21.days: 1
td43     : 2:00:00
td43.days: 0

以上です。

参考

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?