Rafi Shiek
Rafi Shiek

Reputation: 53

Python - How to subtract two dates string and convert the result to milliseconds

I want to subtract two dates and convert the results to milliseconds, I can subtract two dates but not sure how to convert to milliseconds, for example the final output of below code is '0:11:27.581293', I want to convert this to unit in milliseconds, example 12400ms like that, please help.

>>> import dateutil.parser as dparser
>>> stime='2019-04-23 04:22:50.421406'
>>> etime='2019-04-23 04:34:18.002699'
>>> str((dparser.parse(etime, fuzzy=True) - dparser.parse(stime, fuzzy=True)))
'0:11:27.581293'

Expected results: convert '0:11:27.581293' to milliseconds.

Upvotes: 0

Views: 61

Answers (2)

Rakesh
Rakesh

Reputation: 82765

Use total_seconds() * 1000

Ex:

import dateutil.parser as dparser
stime='2019-04-23 04:22:50.421406'
etime='2019-04-23 04:34:18.002699'
print((dparser.parse(etime, fuzzy=True) - dparser.parse(stime, fuzzy=True)).total_seconds() * 1000)
#or 
print(int((dparser.parse(etime, fuzzy=True) - dparser.parse(stime, fuzzy=True)).total_seconds()* 1000))

Output:

687581.293
687581

Upvotes: 1

Srikant
Srikant

Reputation: 294

Use the code below which returns the difference in time in microseconds. Divide by 1000 to get to milliseconds.

diff = dparser.parse(etime, fuzzy=True) - dparser.parse(stime, fuzzy=True)
print(diff.microseconds)

Upvotes: 0

Related Questions