0%
一、时分秒字符串转换成秒数
方法一
1 2 3 4 5 6 7 8
| beginTime = "08:30:30" endTime = "9:33:33"
def t2s(t): h,m,s = t.strip().split(":") return int(h) * 3600 + int(m) * 60 + int(s)
print(t2s(beginTime))
|
方法二
1 2 3 4 5 6 7 8 9 10
| import datetime
beginTime = "08:30:30" endTime = "9:33:33"
def time2sec(x): formatter = ("hours","minutes","seconds") int(datetime.timedelta(**{k:int(v) for k,v in zip(formatter,x.strip().split(":"))}).total_seconds())
print(time2sec(beginTime))
|
其他stackoverflow上的方法:
- 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
二、秒数转换成时分秒字符串
方法一
1 2 3
| >>> import datetime >>> str(datetime.timedelta(seconds=666)) '0:11:06'
|
方法二
1 2 3
| m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s)
|