Search code examples
pythondatetimetimepython-2.4strptime

Compare datetime.datetime to time.strptime


I have the following code:

nowtime = datetime.datetime.now()
newTime = time.strptime(myTimestring, '%Y-%m-%d %H:%M:%S')

if(newTime > nowTime):
  #do some stuff

Of course, my comparison fails with a TypeError, "can't compare datetime.datetime to tuple.". Note that I am using an older version of Python that doesn't have datetime.strptime(). How can I get this comparison to work?


Solution

  • From the datetime.datetime.strptime() documentation:

    This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])).

    For older Python versions (e.g. 2.3 or 2.4), use just that:

    import datetime
    import time
    
    datetime.datetime(*(time.strptime(myTimestring, '%Y-%m-%d %H:%M:%S')[:6]))
    

    Demo:

    >>> import datetime
    >>> import time
    >>> myTimestring = '2013-01-01 12:42:23'
    >>> datetime.datetime(*(time.strptime(myTimestring, '%Y-%m-%d %H:%M:%S')[:6]))
    datetime.datetime(2013, 1, 1, 12, 42, 23)