English 中文(简体)
Python 时间转换 h: m: s 至 秒
原标题:Python Time conversion h:m:s to seconds

我知道在时间delta 函数下, 您可以将秒转换为 h: m: s, 使用诸如 :

>> import datetime
>> str(datetime.timedelta(seconds=666)) 
 0:11:06 

但我需要转换 h: m: s to seconds, or minutes. 但我需要转换 h: m: s to seconds, or minutes。

你知道一个能做到这一点的函数吗?

最佳回答
def hms_to_seconds(t):
    h, m, s = [int(i) for i in t.split( : )]
    return 3600*h + 60*m + s
问题回答
>>> 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

如果你真的想分头行动的话,这里就有一行内衣,一行厚颜无耻,一行内衣。

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

不幸的是,它不如用 datetime.strptime 来从字符串中构建 datetime.strptime 对象那么微不足道。 这个问题以前在Stack Overflow这里被问到 : python-dateutil

或者,如果您不想添加另一个模块, 您可以从字符串中解析 timedelta 。 < a href="http://kbyanc.blogspot.ca/2007/ 08/python- reconstructing- timedeltas-from.html" rel=“ nofollow noreferrerr" > >http://kbyanc.blogspot.ca/2007/ 08/python- reconstructing-timedeltas-from.html 。

>>> def tt(a):
...     b = a.split( : )
...     return int(b[0]) * 3600 + int(b[1]) * 60 + int(b[2])
... 
>>> print tt( 0:11:06 )

666) 666

这在2.6.4中工作:

hours, minutes, seconds = [int(_) for _ in thestring.split( : )]

如果你想把它变回时空 :

thetimedelta = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)

我甚至不确定我是否会为这个 费时间delta费心

>>> pseconds = lambda hms:sum(map(lambda a,b: int(a)*b,hms.split( : ),(3600,60,1)))
>>> pseconds( 0:11:06 )
666

您不需要导入任何东西!

def time(s):
  m = s // 60
  h = (m // 60) % 60
  m %= 60
  s %= 60
  return h,m,s

如果您想要能够处理像 23:32 07 这样的字符串,那么您可以使用以下函数:

def get_seconds(time_string):
    time_list = time_string.split( : )
    seconds = 0 
    for i in range(len(time_list),0,-1):
        t = int(time_list[i-1])*60**(time_len-(i))
        seconds += t
    return seconds




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签