โมดูล time ใน Python เป็นเครื่องมือสำหรับทำงานกับเวลา เช่น การหยุดเวลาการทำงานของโปรแกรม (delay), การบันทึกเวลา, การคำนวณเวลาที่ผ่านไป เป็นต้น โมดูลนี้มีฟังก์ชันที่หลากหลายในการจัดการเกี่ยวกับเวลา เราสามารถนำไปประยุกต์ใช้ได้หลายรูปแบบตามความต้องการของโปรแกรม
ฟังก์ชันหลักใน time และตัวอย่างการใช้งาน
time.time() ฟังก์ชันนี้จะคืนค่าเวลาปัจจุบันในรูปแบบของเวลาที่วัดจาก “Epoch” (มักเป็นเวลา 00:00:00 UTC ของวันที่ 1 มกราคม 1970)
import time
current_time = time.time()
print(f"Current Epoch time: {current_time}")time.sleep(seconds) ฟังก์ชันนี้จะหยุดการทำงานของโปรแกรมตามเวลาที่ระบุในหน่วยวินาที (seconds)
import time
print("Start")
time.sleep(2) # หยุด 2 วินาที
print("End")time.localtime([seconds]) คืนค่าเวลาปัจจุบันในรูปแบบโครงสร้างเวลา (time.struct_time) ถ้าไม่มีการส่งค่ามาในพารามิเตอร์ seconds จะใช้เวลาปัจจุบัน
import time
current_local_time = time.localtime()
print("Current local time:", current_local_time)time.strftime(format[, t]) แปลงเวลาเป็นสตริงตามรูปแบบที่กำหนด โดยใช้พารามิเตอร์ format เช่น %Y สำหรับปี, %m สำหรับเดือน เป็นต้น
import time
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("Formatted time:", formatted_time)time.strptime(string, format) แปลงสตริงเป็นโครงสร้างเวลา (time.struct_time) ตามรูปแบบที่กำหนด
import time
time_string = "2024-09-28 12:45:00"
time_struct = time.strptime(time_string, "%Y-%m-%d %H:%M:%S")
print("Parsed time structure:", time_struct)time.mktime(t) แปลงโครงสร้างเวลา (time.struct_time) กลับเป็นเวลาในรูปแบบ Epoch (วินาที)
import time
time_struct = time.localtime()
epoch_time = time.mktime(time_struct)
print("Epoch time:", epoch_time)time.monotonic() คืนค่าเวลาที่ผ่านไปตั้งแต่ระบบเริ่มต้นทำงาน (ใช้วัดเวลาโดยไม่เปลี่ยนตามการตั้งค่านาฬิกาของระบบ)
import time
start = time.monotonic()
time.sleep(1)
end = time.monotonic()
print(f"Elapsed time: {end - start} seconds")time.perf_counter() วัดเวลาที่มีความละเอียดสูงที่สุดใน Python สำหรับใช้วัดความเร็วของโค้ด
import time
start = time.perf_counter()
time.sleep(1)
end = time.perf_counter()
print(f"Elapsed time: {end - start} seconds")time.process_time() ใช้วัดเวลาการประมวลผลของ CPU สำหรับโปรแกรม ไม่รวมเวลาที่ใช้ในฟังก์ชัน sleep หรือรอ I/O
import time
start = time.process_time()
for _ in range(1000000):
pass
end = time.process_time()
print(f"CPU processing time: {end - start} seconds")