← Back to team overview

sikuli-driver team mailing list archive

Re: [Question #270830]: How to get difference of 2 dates in python

 

Question #270830 on Sikuli changed:
https://answers.launchpad.net/sikuli/+question/270830

sithjac posted a new comment:
Just visit this link for better understanding https://docs.python.org/2/library/datetime.html#
and to know more about python https://intellipaat.com/tutorial/python-tutorial/introduction/

Definitely datetime is what you need here. Specifically, the strptime
function, which parses a string into a time object.

from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

That gets you a timedelta object that contains the difference between
the two times.  e.g. converting it to seconds or adding it to another
datetime.

It will return a negative result if the end time is earlier than the
start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the
code to assume the interval crosses midnight in this case (i.e. it
should assume the end time is never earlier than the start time), you
can add the following lines to the above code for get rid of this issue:

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

Note: You need to include from datetime import timedelta somewhere).

-- 
You received this question notification because your team Sikuli Drivers
is an answer contact for Sikuli.