Using Python to realize the mutual conversion method of time hours, minutes, seconds and seconds

高洛峰
Release: 2017-03-20 13:29:10
Original
6920 people have browsed it

Inspired by UnixTimestamp, I found that it is very easy to process the time after it is converted into seconds. It is no longer processed in the form of string in the program, regardless of the time It is very convenient to add, subtract or obtain random time points.
If necessary, it is also easy to convert to the required time format.

One: Convert time to seconds

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))
Copy after login

Two: Convert seconds to hours, minutes and seconds:

The following method is copied from stackoverflow.

m, s = pmod(seconds, 60)
h, m = pmod(m, 60)
print ("%02d:%02d:%02d" % (h, m, s))
Copy after login


The above is the detailed content of Using Python to realize the mutual conversion method of time hours, minutes, seconds and seconds. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!