Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python แปลงวินาทีเป็นชั่วโมง นาที และวินาที

ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง

ข้อกำหนดปัญหา: เราได้รับเวลา ต้องแปลงวินาทีเป็นชั่วโมง & นาที เป็นวินาที

มี 3 วิธีตามที่อภิปรายด้านล่าง

วิธีที่ 1: Brute-force method

ตัวอย่าง

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

# formatting
n = 23451
print(convert(n))

ผลลัพธ์

06:30:51

วิธีที่ 2: โมดูล datetime

ตัวอย่าง

# using date-time module
import datetime

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

n = 23451
print(convert(n))

ผลลัพธ์

6:30:51

วิธีที่ 3: โมดูล time

ตัวอย่าง

# using time module
import time

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

n = 23451
print(convert(n))

ผลลัพธ์

06:30:51

สรุป

ในบทความนี้ เราได้เรียนรู้ 3 วิธีแปลงวินาทีเป็นชั่วโมง นาที วินาที: คำนวณเอง, datetime.timedelta, time.strftime