user974703
user974703

Reputation: 1653

comparing times with datetime

I'm new to python, and I'm trying to use a time in a while statement.

while hours_left is greater than 0:00
{
    do some stuff
    decrement hours_left
}

is what I'm trying to achieve.

however I can't just say hours_left > 0 because it's an int.

any ideas how I can type 0:00 as datetime?

Thanks!

Upvotes: 0

Views: 4127

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336078

You want a timedelta object.

import datetime
current_time = datetime.datetime(2011,12,12,12,0,0) # High Noon!
end_time = datetime.datetime(2011,12,25,0,0,0)      # Santa?
while end_time-current_time > datetime.timedelta(0):
    do_stuff()
    current_time = current_time - datetime.timedelta(hours=1)

Upvotes: 2

Travis J
Travis J

Reputation: 82267

Sure, take a current datetime object, add the hours left to it, and then compare the current object to the new one with the hours left. If the current one is less than the new one then you still have hours left.

Upvotes: 0

Related Questions