是否可以将“ 1-5-6”小时转换为“ 01-05-06”?我需要该格式的当前时间。
import datetime
from datetime import date
data = date.today()
print(data)
agora = datetime.datetime.now()
print(agora)
hora = agora.hour
minuto = agora.minute
segundo = agora.second
print('{}-{}-{}'.format(hora, minuto, segundo))
答案 0 :(得分:3)
只需使用strftime
:
from datetime import datetime
agora = datetime.now()
print(agora.strftime('%H-%M-%S'))
输出:
09-59-58
答案 1 :(得分:1)
或仅使用:
print(str(agora).split()[-1])
演示:
import datetime
agora = datetime.datetime.now()
print(str(agora).split()[-1])
输出:
10:03:04.083606
如果您关心毫秒+微秒,请使用:
import datetime
agora = datetime.datetime.now()
print(str(agora).split()[-1].split('.')[0])
输出:
10:03:04
答案 2 :(得分:1)
要将前导零添加到格式字符串,可以使用:02d
。 0
指定使用前导零:
print('{:02d}-{:02d}-{:02d}'.format(hora, minuto, segundo))
import datetime
from datetime import date
data = date.today()
print(data)
agora = datetime.datetime.now()
print(agora)
hora = agora.hour
minuto = agora.minute
segundo = agora.second
print('{:02d}-{:02d}-{:02d}'.format(hora, minuto, segundo))
2019-05-06
2019-05-06 19:06:06.459819
19-06-06