我有一个string变量some_time = "12:30",我想给它加上 2 个小时,所以结果是"14:30".
我相信首先将字符串转换为时间格式,
temp_time = datetime.datetime.strptime(thetime, '%H:%M').time()
Run Code Online (Sandbox Code Playgroud)
以便
>>>print (temp_time)
12:30:00
Run Code Online (Sandbox Code Playgroud)
然后用Pytz就可以解决了。但我似乎找不到单独处理 hh:mm 的 Pytz 命令,没有 yy:dd:mm
任何解决方案?
如果您使用timedelta,则可以添加两个小时,例如:
def add_two_hours(time_string):
the_time = dt.datetime.strptime(time_string, '%H:%M')
new_time = the_time + dt.timedelta(hours=2)
return new_time.strftime('%H:%M')
Run Code Online (Sandbox Code Playgroud)
import datetime as dt
print(add_two_hours('12:30'))
print(add_two_hours('23:30'))
Run Code Online (Sandbox Code Playgroud)
14:30
01:30
Run Code Online (Sandbox Code Playgroud)