受到Unix時(shí)間戳的啟發(fā),我發(fā)現(xiàn)時(shí)間轉(zhuǎn)成秒數(shù)后會(huì)非常好處理,在程序當(dāng)中不再是以字符串的形式處理,不管時(shí)間的加減還是獲取隨機(jī)的時(shí)間點(diǎn)都變得非常方便,
如果有需要,也很容易轉(zhuǎn)換成需要的時(shí)間格式。

一:時(shí)間轉(zhuǎn)成秒數(shù)

st = "08:30:30"
et = "9:33:33"

#方法一
def t2s(t):
    h,m,s = t.strip().split(":")
    return int(h) * 3600 + int(m) * 60 + int(s)

print(t2s(st))

#方法二
import datetime
var = ("hours","minutes","seconds")
time2sec = lambda x:int(datetime.timedelta(**{k:int(v) for k,v in zip(var,x.strip().split(":"))}).total_seconds())

print(time2sec(st))

stackoverflow.com上還有更多的寫法,有興趣可以自己去看。當(dāng)然方法一最簡(jiǎn)單明了,直接用這樣的方法是最好的。

http://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python
http://stackoverflow.com/questions/6402812/how-to-convert-an-hmmss-time-string-to-seconds-in-python

二:秒數(shù)轉(zhuǎn)成時(shí)分秒:

下面的方法是從stackoverflow上抄過(guò)來(lái)的。
http://stackoverflow.com/questions/775049/python-time-seconds-to-hms

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print ("%02d:%02d:%02d" % (h, m, s))

下篇再寫轉(zhuǎn)成時(shí)間轉(zhuǎn)成秒數(shù)后能用來(lái)干嘛。
見(jiàn) python獲取指定時(shí)間段內(nèi)的隨機(jī)不重復(fù)的時(shí)間點(diǎn) http://www.rzrgm.cn/gayhub/p/6158998.html
2016-12-10 0:21:56 codegay