我有两个datetime.time对象,我想计算它们之间的小时差异。例如
a = datetime.time(22,00,00)
b = datetime.time(18,00,00)
我希望能够减去这些值,以便它给出值4。
答案 0 :(得分:12)
要计算差异,您必须将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
答案 1 :(得分:1)
这就是我的做法
a = '2200'
b = '1800'
time1 = datetime.strptime(a,"%H%M") # convert string to time
time2 = datetime.strptime(b,"%H%M")
diff = time1 -time2
diff.total_seconds()/3600 # seconds to hour
输出:4.0
答案 2 :(得分:1)
我从这个问题中得到了结果:
a='2017-10-10 21:25:13'
b='2017-10-02 10:56:33'
a=pd.to_datetime(a)
b=pd.to_datetime(b)
c.total_seconds()/3600
但无法正常工作:
table1['new2']=table1['new'].total_seconds()/3600