1

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?

junkfoodjunkie
  • 3,168
  • 1
  • 19
  • 33
  • Try this `current_hour = str(int(hour[:2])+1)+hour[2:]`. But, it will fail at edge cases i.e when the hour is `12:00` etc. So, better use `Datetime` – Arunesh Singh Nov 27 '17 at 05:04

2 Answers2

3

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
MKRNaqeebi
  • 573
  • 10
  • 16
0

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'
Turksarama
  • 199
  • 2
  • Problem with this is that the variables are stored as strings in the Ren'Py game-engine. Maybe there is a way to use it as a datetime-object, I don't know. Your solution works great by itself, but when I try to use datetime with stored variables, it gets messy, fast. – junkfoodjunkie Nov 27 '17 at 05:39