บทนำ
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 20212. หน่วงเวลา (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