Python,以(HH:MM:SS-HH:MM:SS)格式减去两个不同的时间 [英] Python, subtract two different times in the format (HH:MM:SS - HH:MM:SS)
问题描述
我需要减去两个不同的时间,以得到差异.例如说我有message.start和message.end,它们都是日期和时间(但它们都是'time'类型.我在python中使用 type(message.start)
进行了检查),并采用以下格式:月/日/年HH:MM:SS",例如(16/11/16 13:32:00)
I need to subtract two different times, to get the difference. For example say I have message.start and message.end, both of which are a date and time (but they are of type 'time'. I checked this using type(message.start)
in python) and are in the following format: 'month/day/year HH:MM:SS' so for example (08/11/16 13:32:00)
在下面的代码中,我将它们转换为字符串,因为我需要拆分日期和时间,并进一步拆分代码中其他不需要在此处显示的部分的日期.我在message.end-message.start上尝试了一些方法,但这也不起作用.
In the code below I convert them to strings as I need to split up the date and time, and further split the date for other parts of the code which I don't need to show here. I tried something along message.end - message.start but that didn't work either.
我只需要时差,所以说我有08/11/16 18:30:00-08/11/16 12:00:00,这应该导致6.5或6hrs30mins
I just need the time difference, so say I have 08/11/16 18:30:00 - 08/11/16 12:00:00, this should result in 6.5 or 6hrs30mins
我该怎么办?
这是我的代码:
startDateTime = str(message.start).split()
startTime = startDateTime[1]
startDate = startDateTime[0].rsplit("/")
endDateTime = str(message.end).split()
endTime = endDateTime[1]
endDate = endDateTime[0].rsplit("/")
推荐答案
您需要 datetime
中的 strptime
方法.
import datetime
format = '%m/%d/%y %H:%M:%S'
startDateTime = datetime.datetime.strptime(message.start, format)
endDateTime = datetime.datetime.strptime(message.end, format)
diff = endDateTime - startDateTime
输出:
>>> start='08/11/16 12:00:00'
>>> format = '%m/%d/%y %H:%M:%S'
>>> startDateTime = datetime.datetime.strptime(start, format)
>>> end='08/11/16 18:30:00'
>>> endDateTime = datetime.datetime.strptime(end, format)
>>> diff = endDateTime - startDateTime
>>> print diff
6:30:00
这篇关于Python,以(HH:MM:SS-HH:MM:SS)格式减去两个不同的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!