1

好吧,我真的不知道这个标题是什么。我有一个游戏,我通过变量手动更新时间。 $ current_hour = "07:00"例如

我想要做的是增加这个,而不必每次都手动输入新的时间。像这样的东西:( $ current_hour += 1我知道这当然行不通)

所以,我尝试如下:

hour = current_hour
current_hour = str(int(hour[:2]+1)+hour[3:])

然后,希望能给我 08:00 - 但它不起作用,我对为什么有点难过。我得到的错误是coercing to unicode, need string or buffer, int found 我认为我分别声明为 int() 和 str() 来解决这个问题,但显然我没有。所以,我很讨厌 Python——有人能帮忙吗?

4

2 回答 2

3

尝试这个:

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
于 2017-11-27T05:20:02.857 回答
0

不要重新发明轮子,而是使用日期时间对象。

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'
于 2017-11-27T05:15:26.230 回答