Yannis
Yannis

Reputation: 1721

Subtract datetime objects to get numerical result in milliseconds (Python)

Trying to find the elapsed time from two strings which hold a timestamp and are in the format hh:mm:ss.mss. Basically, I want to subtract two datetime objects and get a numerical result in milliseconds.

Here is my code:

from datetime import datetime

elapsed_time = 0
s = '13:46:34.550'
e = '13:46:36.750'

# only interested on the time part, not the 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 I get a TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'int'.

It should print 00:00:02.250 or (ideally) 2200.

Any ideas what I am doing wrong?

Upvotes: 4

Views: 6554

Answers (1)

user6613600
user6613600

Reputation:

The following worked for me (using Python 3.5.2):

from datetime import datetime

elapsed_time = 0
s = '13:46:34.550'
e = '13:46:36.750'

# only interested on the time part, not the 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 I got was 2200 which is the time difference in milliseconds between s and e

Some references:

Python: Difference between two datetimes in milliseconds (Mark Needham's blog)

Python docs about datetime

A bit of explanation from the docs (linked immediately above):

In section 8.1.4 datetime Objects, it states that for the operation:

timedelta = datetime1 - datetime2

(which corresponds to the 2nd last line of code in this answer):

Subtraction of a datetime from a datetime is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, TypeError is raised.

Also:

Changed in version 3.3: Equality comparisons between naive and aware datetime instances don’t raise TypeError

Upvotes: 6

Related Questions