0

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 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?

Daniel
  • 5,095
  • 5
  • 35
  • 48
DavidJB
  • 2,272
  • 12
  • 30
  • 37
  • What do you mean you don't know how to construct a timedelta object? Have you looked at the docs? Have you even tried? – Falmarri Feb 02 '15 at 22:33

1 Answers1

5

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.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395