LoginSignup
1
0

More than 3 years have passed since last update.

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'となったときの対応方法

Posted at
  • 環境
    • macOS Catalina バージョン10.15.7
    • Python 3.8.5
    • pandas 1.1.3

事象 : TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

時間を引き算したら怒られた

Traceback (most recent call last):
  File "/Users/mananakai/tryPython/main.py", line 30, in calc_diff
    diff = end - start
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
def calc_diff(start, end):
    diff = end - start
    print(diff)

原因 : datetime.timeとdatetime.dateはそのままじゃ計算できない

時間情報(datetime.time)、日付情報(datetime.date)だけでは計算できない。
計算には、日時情報(datetime.datetime)を使う。

対応 : datetime.datetimeに変換して計算する

計算結果は、時刻間の差情報(datetime.timedelta)になる

def calc_diff(start, end):
    today = datetime.date.today()
    d_start = datetime.datetime.combine(today, start)
    d_end = datetime.datetime.combine(today, end)
    diff = d_end - d_start
    print(type(diff)) # >> <class 'datetime.timedelta'>
1
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
1
0