如何将整数转换为时间

时间:2019-10-07 15:37:32

标签: python python-3.x

我有几个小时的时间,如下所示

小时:

0
1
2
3
4
5
6
7
8
9
10
11
12
14
15
16
17
18
19
20
21
22
23

我希望有这样的时间:

00:00:00
01:00:00
02:00:00
03:00:00 etc

3 个答案:

答案 0 :(得分:0)

这是使用pandasdatetime python库的解决方案。希望对您有帮助

代码:

import pandas as pd
from datetime import datetime
hour = 13
a = pd.to_datetime(hour, format='%H')
converted_time = a.strftime("%H:%M:%S")
print(converted_time)

输出

13:00:00

答案 1 :(得分:0)

只需使用time中的datetime

In [1]: from datetime import time

In [2]: for i in range(4):
   ...:     t = time(i, 0, 0)
   ...:     print(t.strftime('%H:%M:%S'))
   ...:

00:00:00
01:00:00
02:00:00
03:00:00

答案 2 :(得分:0)

您可以将datetime与它的功能strptime一起使用。这样使用:

from datetime import datetime

t = datetime.strptime(str(your_int), "%H")
print(t.strftime("%H"))

使用strptime很有用,因为如果您更改了int格式,则仍可以使用https://docs.python.org/2/library/datetime.html?highlight=datetime#strftime-strptime-behavior

此处提供的不同代码将其直接格式化为日期。
相关问题