簡體   English   中英

如何使用 datetime 將 int 轉換為時間

[英]How can I convert int to time using datetime

我有一個這種格式的列表:

L = [445, 650, 920, 1130, 1340]

結果將是:

['4:45', '6:50', '9:20', '13:40']

我試過這個:

length = len(L)
L1 = str(L)
for i in range(length):
    tm = datetime.strptime(L1[i], '%H%M').time()
    print(tm)

該輸入有點奇怪,您確定它不是十進制時間,例如450是 450mn (7h30),還是 4.45h aka 4h27?

如果您確定輸入的描述正確,那么您可以使用divmod(n, 100)將您的時間分成兩部分(除以 100 的整數部分,其余部分),然后將這兩個值放入timetimedelta的相關字段:

L = [445, 650, 920, 1130, 1340]
for v in L:
    h, m = divmod(v, 100)
    print(datetime.time(hour=h, minute=m))
04:45:00
06:50:00
09:20:00
11:30:00
13:40:00

作為日期時間沒有意義,日期時間必須完全填充日期部分,盡管您可以時間與參考date結合起來以獲得datetime時間。

您可以使用 datetime 模塊中的時間 class 來執行此操作。 使用方法 strftime 將時間數據轉換為您想要的任何 str 格式。

from datetime import time


def time_int_to_str(time_int):
    hour, minute = divmod(time_int, 100)
    t = time(hour=hour, minute=minute)
    time_str = t.strftime("%H:%M")
    return time_str[1:] if time_str[0] == "0" else time_str  # get rid of 0 at the start (e.g. 01:00 -> 1:00, and protection in case of 00:00)

通過您提供的示例:

L = [445, 650, 920, 1130, 1340]
[time_int_to_str(example) for example in L]

我們收到:

['4:45', '6:50', '9:20', '11:30', '13:40']

你可以嘗試這樣的事情:

get_time = lambda time: str(time)[:-2] + ':' + str(time)[-2:]
list(map(get_time,L))

['4:45', '6:50', '9:20', '11:30', '13:40']

from datetime import datetime
get_time = lambda time: datetime.strptime(str(time)[:-2] + ':' + str(time)[-2:], '%H:%M').time()
res = list(map(get_time,L))
res

[datetime.time(4, 45),
 datetime.time(6, 50),
 datetime.time(9, 20),
 datetime.time(11, 30),
 datetime.time(13, 40)]

理解

[ str(item)[:len(str(item)) - 2] + ':' + str(item)[len(str(item)) - 2:] for item in L  ]

['4:45', '6:50', '9:20', '11:30', '13:40']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM