簡體   English   中英

在python中將時間(HH:MM:SS)轉換為分鍾

[英]Convert time (HH:MM:SS) to minutes in python

如何將 HH:MM:SS 轉換為分鍾?

我試過下面工作正常:

  import datetime as DT
  t1 = DT.datetime.strptime('0:10:00', '%H:%M:%S')

我嘗試了另一個示例並收到錯誤:

  import datetime as DT
  t1 = DT.datetime.strptime('9715:56:46', '%H:%M:%S')

錯誤:

  ValueError: time data '9715:56:46' does not match format '%H:%M:%S'

在這個例子中,它支持 %H 的最大 23,如果我的小時數超過 23(在這種情況下我有 9715 小時)如何得到它?

datetime.datetime是時間點的表示,而不是持續時間。

datetime.timedelta是時間長度的表示。 觀察:

from datetime import timedelta


delta = timedelta(hours=9715, minutes=56, seconds=46)
total_seconds = delta.total_seconds()
minutes = int(total_seconds // 60)
seconds = int(total_seconds % 60)

print('{minutes}:{seconds}'.format(minutes=minutes, seconds=seconds))

編輯:我更改了代碼以使用 python 2.7。

您可以將sum與生成器表達式或map

from operator import mul

my_time = '9715:56:46'
factors = (60, 1, 1/60)

t1 = sum(i*j for i, j in zip(map(int, my_time.split(':')), factors))
t2 = sum(map(mul, map(int, my_time.split(':')), factors))

print(t1)  # 582956.7666666667

assert t1 == t2

正如錯誤所說,您提供了錯誤的小時值。

它必須 >=0 且 < 24。

[ https://docs.python.org/2/library/datetime.html][1]

轉換為分鍾:

input_time='9715:56:46'
t=input_time.split(':')

total_minutes= int(t[0])*60+int(t[1])*1 +int(t[2])/60

strptime函數(在其各種化身中)並非設計用於執行此類任務,它僅用於解析有效的時間/日期字符串。

簡單的解決方案是編寫自己的代碼來解析字符串並執行算術運算。 這是一個輸出秒的例子; 顯然你可以除以 60 得到分鍾。

def hms_to_s(s):
    t = 0
    for u in s.split(':'):
        t = 60 * t + int(u)
    return t

data = (
    '10',
    '0:10',
    '1:30',
    '2:1:00',
    '1000:00:00',
    '9700:00:00',
    '15:56:46',
    '9715:56:46',
)

for s in data:
    print(s, hms_to_s(s)) 

輸出

10 10
0:10 10
1:30 90
2:1:00 7260
1000:00:00 3600000
9700:00:00 34920000
15:56:46 57406
9715:56:46 34977406

簡單的支持 d:h:m:s / h:m:s / m:s / s !

def dhms_to_sec(dhms_str):
    '''supports also format of d:h:m:s, h:m:s, m:s and s'''
    _,d,h,m,s = (':0'*10+dhms_str).rsplit(':',4)
    return int(d)*24*60*60+int(h)*60*60+int(m)*60+int(s) 

# examples:
print(dhms_to_sec('04'))  # will print 4
print(dhms_to_sec('1:04'))  # will print 64
print(dhms_to_sec('1:01:04'))  # will print 3664
print(dhms_to_sec('1:1:4'))  # will print 3664

您可以通過 /60 將其轉換為分鍾......它也將接受像 1:56:0 這樣的奇怪情況

假設您想將字符串“01:21:48”轉換為分鍾。

from datetime import timedelta

h = "01:21:48"
delta = timedelta(hours=int(h.split(':')[0]), minutes=int(h.split(':')[1]), seconds=int(h.split(':')[2]))
minutes = delta.total_seconds()/60
print(minutes)

所以打印出來的結果是:81.8

您對庫及其工作方式有一個糟糕的概念,看,第一個參數是一天中的小時,格式為 00-23,例如 22 是晚上 10 點,因此有效小時數從 00 到 23,另一個輸入是無效輸入。

例子:

import datetime as DT
t1 = DT.datetime.strptime('23:56:46', '%H:%M:%S')

觀察:

第一個值可以是000 ,但000也會產生相同的錯誤:

t1 = DT.datetime.strptime('0:56:46', '%H:%M:%S') # it's ok
t1 = DT.datetime.strptime('00:56:46', '%H:%M:%S') # it's ok
t1 = DT.datetime.strptime('000:56:46', '%H:%M:%S') # same error you got
i = "15:21"
sp = i.split(":")
minutes = 0.0
if len(sp) == 3:
    minutes = minutes + int(sp[0]) * 60
    minutes = minutes + int(sp[1])
    minutes = minutes + int(sp[2]) / 60
elif len(sp) == 2:
    minutes = minutes + int(sp[0])
    minutes = minutes + int(sp[1]) / 60
elif len(sp) == 1:
    minutes = minutes + int(sp[0]) / 60
print(minutes)

一個很好的解決方案:)

暫無
暫無

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

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