Skip to content Skip to sidebar Skip to footer

Compare If Datetime.timedelta Is Between Two Values

I have a datetime.timedelta time object in python (e.g. 00:02:00) I want to check if this time is less than 5 minutess and greater then 1 minute. I'm not sure how to construct a ti

Solution 1:

So if you start with a string that's rigorously and precisely in the format 'HH:MM:SS', timedelta doesn't directly offer a string-parsing function, but it's not hard to make one:

import datetime

defparsedelta(hhmmss):
    h, m, s = hhmmss.split(':')
    return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))

If you need to parse many different variants you'll be better off looking for third-party packages like dateutil.

Once you do have timedelta instance, the check you request is easy, e.g:

onemin = datetime.timedelta(minutes=1)
fivemin = datetime.timedelta(minutes=5)

if onemin < parsedelta('00:02:00') < fivemin:
    print('yep')

will, as expected, display yep.

Post a Comment for "Compare If Datetime.timedelta Is Between Two Values"