Python数字字符串到时间转换

时间:2016-05-19 10:46:23

标签: python time

我正在尝试将字符串转换为时间,

 i have the following string,

 0100 will have to give time 01:00:00
 0130 will have to give time 01:30:00 likewise,

任何人都知道我正在尝试这个

from datetime import datetime
import time

p = "0100"
op = time.strftime("%H:%M:%S", time.gmtime(float(p)) )

给我输出像00:01:40

我怎样才能达到理想的效果

1 个答案:

答案 0 :(得分:2)

使用time.strptime格式化表示时间的字符串,然后使用time.strftime将其转换回所需的格式:

>>> time.strftime("%H:%M:%S", time.strptime("0100", "%H%M"))
'01:00:00'
>>> time.strftime("%H:%M:%S", time.strptime("0130", "%H%M"))
'01:30:00'
>>> time.strftime("%H:%M:%S", time.strptime("2130", "%H%M"))
'21:30:00'