Python时间转换h:m:s到秒

Gep*_*ada 8 python formatting datetime

我知道使用timedelta函数你可以使用类似的东西将秒转换为h:m:s:

>> import datetime
>> str(datetime.timedelta(seconds=666)) 
'0:11:06'
Run Code Online (Sandbox Code Playgroud)

但我需要将h:m:s转换为秒或分钟.

你知道一个可以做到这一点的功能吗?

Hug*_*ell 13

def hms_to_seconds(t):
    h, m, s = [int(i) for i in t.split(':')]
    return 3600*h + 60*m + s
Run Code Online (Sandbox Code Playgroud)


Nol*_*lty 12

>>> import time, datetime
>>> a = time.strptime("00:11:06", "%H:%M:%S")
>>> datetime.timedelta(hours=a.tm_hour, minutes=a.tm_min, seconds=a.tm_sec).seconds
666
Run Code Online (Sandbox Code Playgroud)

如果你真的打算分裂":",那么这是一个厚脸皮的衬垫

>>> s = "00:11:06"
>>> sum(int(i) * 60**index for index, i in enumerate(s.split(":")[::-1]))
666
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果小时数超过23,则会失败. (3认同)