是否有办法将“ 1-5-6”小时转换为“ 01-05-06”?(仅举一个例子)

时间:2019-05-07 01:58:10

标签: python format hour

是否可以将“ 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))

3 个答案:

答案 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)

要将前导零添加到格式字符串,可以使用:02d0指定使用前导零:

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