Search code examples
pythontimedelta

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 minutes and greater then 1 minute.

I'm not sure how to construct a timedelta object and I'm also not sure if this is the right format to compare times. Would anyone know the most efficient way to do this?


Solution

  • 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
    
    def parsedelta(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.