Subtract datetime objects to get numerical result in milliseconds (Python) -
trying find elapsed time 2 strings hold timestamp , in format hh:mm:ss.mss
. basically, want subtract 2 datetime
objects , numerical result in milliseconds.
here code:
from datetime import datetime elapsed_time = 0 s = '13:46:34.550' e = '13:46:36.750' # interested on time part, not date start_time = datetime.strptime(s, '%h:%m:%s.%f') end_time = datetime.strptime(e, '%h:%m:%s.%f') #elapsed_time = end_time - start_time #elapsed_time = (end_time - start_time).microsecond
for both elapsed_time
calculations typeerror: unsupported operand type(s) -: 'datetime.datetime' , 'int'
.
it should print 00:00:02.250
or (ideally) 2200
.
any ideas doing wrong?
the following worked me (using python 3.5.2):
from datetime import datetime elapsed_time = 0 s = '13:46:34.550' e = '13:46:36.750' # interested on time part, not date start_time = datetime.strptime(s, '%h:%m:%s.%f') end_time = datetime.strptime(e, '%h:%m:%s.%f') diff = end_time - start_time elapsed_time = int((diff.seconds * 1000) + (diff.microseconds / 1000))
the output got 2200
time difference in milliseconds between s
, e
some references:
python: difference between 2 datetimes in milliseconds (mark needham's blog)
a bit of explanation docs (linked above):
in section 8.1.4 datetime
objects, states operation:
timedelta = datetime1 - datetime2
(which corresponds 2nd last line of code in answer):
subtraction of
datetime
datetime
defined if both operands naive, or if both aware. if 1 aware , other naive,typeerror
raised.
also:
changed in version 3.3: equality comparisons between naive , aware
datetime
instances don’t raisetypeerror
Comments
Post a Comment