Reputation: 3178
Okay, I was really unsure what to title this. I have a game, where I update the time manually, via a variable.
$ current_hour = "07:00"
for instance
What I want to be able to do, is increase this without having to manually enter a new time every time. Something like this:
$ current_hour += 1
(I know this of course won't work)
So, I tried as follows:
hour = current_hour
current_hour = str(int(hour[:2]+1)+hour[3:])
which then, hopefully, would give me 08:00 - but it doesn't work, and I'm a little stumped as to why.
The error I get is coercing to unicode, need string or buffer, int found
I thought I took care of that with the declaring as int() and str() respectively, but obviously I didn't. So, I suck at Python - anyone able to help with this?
Upvotes: 1
Views: 77
Reputation: 593
Try this:
current_hour = "12:00"
current_hour = str(int(current_hour[:2])+1)+current_hour[2:]
if len(current_hour)==4:
current_hour = '0' + current_hour
if int(current_hour[:2]) >= 13:
current_hour = str(int(current_hour[:2])-12)+current_hour[2:]
if len(current_hour)==4:
current_hour = '0' + current_hour
Upvotes: 3
Reputation: 209
Don't reinvent the wheel, and use datetime objects.
from datetime import time
current_hour = time(7)
current_hour # datetime.time(7, 0)
def addhour(time, hours):
return time.replace(hour = (time.hour + hours)%24)
addhour(current_hour, 1) # datetime.time(8, 0)
current_hour.isoformat() # '08:00:00'
Upvotes: 0