0
我有兩個datetime.time對象,我想計算它們之間的小時差。例如Python - 計算兩個datetime.time對象之間的差異
a = datetime.time(22,00,00)
b = datetime.time(18,00,00)
我希望能夠減去這些使得它帶給我的價值4
我有兩個datetime.time對象,我想計算它們之間的小時差。例如Python - 計算兩個datetime.time對象之間的差異
a = datetime.time(22,00,00)
b = datetime.time(18,00,00)
我希望能夠減去這些使得它帶給我的價值4
計算差值,您必須將datetime.time
對象轉換爲datetime.datetime
對象。然後當你減去,你會得到一個timedelta
對象。爲了找出timedelta
物體有多少小時,您必須找到總秒數並將其除以3600
。
# Create datetime objects for each time (a and b)
dateTimeA = datetime.datetime.combine(datetime.date.today(), a)
dateTimeB = datetime.datetime.combine(datetime.date.today(), b)
# Get the difference between datetimes (as timedelta)
dateTimeDifference = dateTimeA - dateTimeB
# Divide difference in seconds by number of seconds in hour (3600)
dateTimeDifferenceInHours = dateTimeDifference.total_seconds()/3600