有什么办法可以将小时“1-5-6”变成“01-05-06”吗?(只是一个例子)

Is there any way to turn the hour '' 1-5-6 '' into '' 01-05-06 " ? (Just an example)

有没有办法把小时“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))

只需使用strftime:

from datetime import datetime
agora = datetime.now()

print(agora.strftime('%H-%M-%S'))

输出:

09-59-58

或者直接使用:

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

要向格式字符串添加前导零,您可以使用 :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