Reputation: 23
I have to read two columns of data from an Excel file, then calculate the difference between each pair and write the answer in a new column in Excel. There is no problem in reading and writing data but I could not subtract two datetime.time
objects from each other.
My data is in the format "16:56:20.09"
and when I try to find the difference between two of them I get the following error:
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
Could you please help me to solve this problem?
Upvotes: 2
Views: 1101
Reputation: 121986
You can't subtract time
instances, because there's no definitive ordering to them; what's the difference between 12.00 and 13.00? An hour? What if I now tell you I mean 12.00 yesterday and 13.00 tomorrow? Hence the error:
>>> from datetime import date, time, datetime
>>> t1 = time(12, 00)
>>> t2 = time(13, 00)
>>> t1 - t2
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
t1 - t2
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
You need to know what day the times occur on to calculate the difference. You need to convert them to datetime
objects by combining them with the appropriate date
:
>>> dt1 = datetime.combine(date(2015, 7, 14), t1)
>>> dt2 = datetime.combine(date(2015, 7, 16), t2)
Now you can subtract them:
>>> dt2 - dt1
datetime.timedelta(2, 3600) # two days, 3,600 seconds
If they're on the same day (or you're assuming they are), it generally* doesn't matter which day, so you can do e.g.
>>> datetime.combine(date.today(), t2) - datetime.combine(date.today(), t1)
datetime.timedelta(0, 3600) # one hour
* (i.e. ignoring changing clocks, leap seconds, ...)
Upvotes: 2