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

การเข้าถึงและแปลงเวลาด้วย Time Library ใน Python

บทนำ

time module ให้ฟังก์ชันจัดการเวลา: current time, sleep, formatting, struct_time object

การเริ่มต้น

import time

ฟังก์ชันหลัก

1. เวลาท้องถิ่นปัจจุบัน

seconds = time.time()           # seconds since epoch (Jan 1 1970)
local_time = time.ctime(seconds)
print("Local time:", local_time)
# Local time: Sun Jan 31 23:50:16 2021

2. หน่วงเวลา (sleep)

for i in range(1, 6):
    print(i)
    time.sleep(1)  # หน่วง 1 วินาที

3. struct_time object

seconds = time.time()
curr_time = time.localtime(seconds)
print(curr_time)
print("Current year ->", curr_time.tm_year)
# time.struct_time(tm_year=2021, tm_mon=1, tm_mday=31, tm_hour=9, tm_min=28, tm_sec=56, tm_wday=6, tm_yday=31, tm_isdst=0)

4. String → struct_time (strptime)

example = "17 July 2001"
ans = time.strptime(example, "%d %B %Y")
print(ans)
# time.struct_time(tm_year=2001, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=198, tm_isdst=-1)

Format Codes พบบ่อย

Codeความหมาย
%Yปี 4 หลัก
%mเดือน 01-12
%dวัน 01-31
%Hชั่วโมง 00-23
%Mนาที 00-59
%Sวินาที 00-59
%Bชื่อเดือนเต็ม
%Aชื่อวันเต็ม

สรุป

time module เหมาะสำหรับ: timestamp, sleep, simple formatting สำหรับ datetime ซับซ้อนกว่า (timezone, arithmetic) ควรใช้ datetime module

เอกสาร: https://docs.python.org/3/library/time.html