Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python chuyển giây thành giờ, phút, giây

Bài toán: cho thời gian tính bằng giây, chuyển đổi thành giờ, phút, giây.

Cách 1: Brute-force (toán học)

def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%02d:%02d:%02d" % (hour, minutes, seconds)

n = 23451
print(convert(n))
06:30:51

Cách 2: Module datetime

import datetime
def convert(n):
    return str(datetime.timedelta(seconds=n))

n = 23451
print(convert(n))
6:30:51

Cách 3: Module time

import time
def convert(seconds):
    return time.strftime("%H:%M:%S", time.gmtime(n))

n = 23451
print(convert(n))
06:30:51

Kết luận

Đã học 3 cách chuyển giây sang giờ:phút:giây: toán học, datetime.timedelta, time.strftime+gmtime.