โมดูล time จัดการเวลาในหลายรูปแบบ: timestamp, struct_time, formatted string ใช้ Epoch time (1 Jan 1970 UTC)
Epoch และ Tick
>> import time
>>> time.gmtime(0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
# Tick = วินาทีจาก Epoch (float)
>>> time.time()
1553262407.0398576
ฟังก์ชันหลัก
1. time.time() - Timestamp ปัจจุบัน
import time
print(time.time()) # 1553262407.0398576
# วัด elapsed time
start = time.time()
time.sleep(0.9)
end = time.time()
print(end - start) # 0.9219...
2. time.clock() - Processor Time (Deprecated in 3.3, Removed in 3.8)
ใช้ time.perf_counter() หรือ time.process_time() แทน
import time
print(time.perf_counter()) # High-resolution wall clock
print(time.process_time()) # CPU time
3. time.ctime() - Human Readable String
>> time.ctime()
'Fri Mar 22 19:43:11 2019'
>>> time.ctime(time.time() + 60)
'Fri Mar 22 19:44:11 2019'
4. time.sleep(seconds) - หยุดการทำงาน
import time
print(time.ctime()) # เริ่มต้น
time.sleep(5)
print(time.ctime()) # 5 วินาทีหลัง
5. time.struct_time - โครงสร้างเวลา
>> t = time.localtime()
>>> t.tm_year, t.tm_mon, t.tm_mday # 2019, 3, 22
>>> t.tm_hour, t.tm_min, t.tm_sec # 20, 10, 25
>>> t.tm_wday # 4 (Mon=0)
>>> t.tm_yday # 81 (day of year)
>>> t.tm_isdst # 0 (no DST)
6. time.strftime() - Format ตามต้องการ
>> now = time.localtime()
>>> time.strftime("%y/%m/%d %H:%M", now)
'19/03/22 20:13'
>>> time.strftime("%a %b %d", now)
'Fri Mar 22'
>>> time.strftime("%c", now)
'Fri Mar 22 20:13:43 2019'
>>> time.strftime("%I %p", now)
'08 PM'
>>> time.strftime("%Y-%m-%d %H:%M:%S %Z", now)
'2019-03-22 20:13:43 India Standard Time'
Timezone Info
>> time.timezone # Offset from UTC (seconds, non-DST) -19800
>>> time.tzname # ('India Standard Time', 'India Daylight Time')
Format Codes สำคัญ
| Code | ความหมาย |
|---|---|
%Y | Year (4 digits) |
%m | Month (01-12) |
%d | Day (01-31) |
%H | Hour (00-23) |
%I | Hour (01-12) |
%M | Minute (00-59) |
%S | Second (00-59) |
%p | AM/PM |
%Z | Timezone name |
%a | Weekday abbreviated |
%b | Month abbreviated |
หมายเหตุ: สำหรับ Date/Time manipulation ที่ซับซ้อน ใช้โมดูล datetime แทน