我需要將字串轉換為小時格式的時間。我嘗試使用以下但我沒有得到我期望的結果。
inp_string = "70:30:00"
print(datetime.strptime(inp_string, "%H:%M:%S").time())
為此,我收到以下錯誤:
ValueError: time data '70:30:00' does not match format '%H:%M:%S'
如果我輸入低于 24 小時的值,我會得到很好的結果;
new = '23:30:00'
print("value:",datetime.strptime(new, "%H:%M:%S").time())
print(type(datetime.strptime(new, "%H:%M:%S").time()))
輸出
value: 23:30:00
<class 'datetime.time'>
像這樣,我必須將字串轉換為小時大于 24 的時間格式。
uj5u.com熱心網友回復:
您需要撰寫自己的決議器來轉換str(timedelta或找到為您執行此操作的庫)。
假設你的持續時間總是喜歡HH:MM:SS,你可以使用這樣的東西:
import datetime
def parse_duration(s):
return list(map(lambda x: int(x), s.split(":")))
inp1 = "70:30:00"
[h1, m1, s1] = parse_duration(inp1)
d1 = datetime.timedelta(hours=h1, minutes=m1, seconds=s1)
inp2 = "00:30:00"
[h2, m2, s2] = parse_duration(inp2)
d2 = datetime.timedelta(hours=h2, minutes=m2, seconds=s2)
res = d1 d2
# Format res however you like
uj5u.com熱心網友回復:
inp_string = "70:30:00"
new_hour=(int(inp_string[0:2]))%24
new_string=str(new_hour) (inp_string[2:8])
print(new_string)
print(datetime.strptime(new_string, "%H:%M:%S").time())
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/429345.html
上一篇:在R時間框架索引中滾動應用
