โมดูล datetime ให้ Classes สำหรับจัดการ Date/Time: date, time, datetime, timedelta, tzinfo, timezone
import datetime
Class Overview
| Class | Attributes | คำอธิบาย |
|---|---|---|
date | year, month, day | วันที่อย่างเดียว (Gregorian Calendar) |
time | hour, minute, second, microsecond, tzinfo | เวลาอย่างเดียว (ไม่ผูกวันที่) |
datetime | date + time attributes | วันที่และเวลารวมกัน |
timedelta | days, seconds, microseconds | ความต่างระหว่าง Date/Time |
tzinfo | Abstract Base Class | Timezone Info |
timezone | Fixed Offset from UTC | Concrete tzinfo (3.2+) |
Constants
datetime.MINYEAR = 1datetime.MAXYEAR = 9999
Date Objects
import datetime as dt # สร้าง Date d = dt.date(1998, 9, 5) print(d) # 1998-09-05 print(d.toordinal()) # 729637 (Days since 0001-01-01) print(d.weekday()) # 5 (Saturday, Mon=0) print(d.isoweekday()) # 6 (Sat, Mon=1) print(d.isoformat()) # '1998-09-05' # Class Methods today = dt.date.today() from_ts = dt.date.fromtimestamp(1609459200) # From Unix Timestamp from_ord = dt.date.fromordinal(732698) # Arithmetic delta = from_ord - d print(delta) # 3061 days, 0:00:00 print(type(delta)) #
Time Objects
t = dt.time(14, 30, 59, 123456)
print(t) # 14:30:59.123456
print(t.hour, t.minute, t.second, t.microsecond)
# Replace
t2 = t.replace(hour=15, minute=0)
print(t2) # 15:00:59.123456
# ISO Format
print(t.isoformat()) # '14:30:59.123456'
print(dt.time.fromisoformat('14:30:59'))
Datetime Objects
# Current
now = dt.datetime.now()
utc_now = dt.datetime.utcnow()
# Specific
dt1 = dt.datetime(2015, 1, 4)
dt2 = dt.datetime(2017, 8, 15)
print(dt1.weekday()) # 6 (Sunday)
print(dt1.strftime('%A')) # 'Sunday'
# Parsing
dt3 = dt.datetime.strptime('August-15-2017', '%B-%d-%Y')
# Difference
diff = dt3 - dt1
print(diff) # 954 days, 0:00:00
print(diff.total_seconds()) # 82425600.0
strftime / strptime Directives
| Directive | ความหมาย | ตัวอย่าง |
|---|---|---|
%Y | Year (4 digits) | 2024 |
%m | Month (01-12) | 01 |
%d | Day (01-31) | 05 |
%H | Hour 24h (00-23) | 14 |
%I | Hour 12h (01-12) | 02 |
%M | Minute (00-59) | 30 |
%S | Second (00-59) | 59 |
%f | Microsecond (000000-999999) | 123456 |
%A | Weekday Full | Sunday |
%a | Weekday Abbrev | Sun |
%B | Month Full | January |
%b | Month Abbrev | Jan |
%z | UTC Offset | +0700 |
%Z | Timezone Name | ICT |
%c | Locale Date/Time | Sun Jan 5 14:30:59 2024 |
%x | Locale Date | 01/05/24 |
%X | Locale Time | 14:30:59 |
Timezone Handling (Python 3.9+ ZoneInfo)
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo # Python 3.9+
# Fixed Offset
tz = timezone(timedelta(hours=7))
dt_tz = datetime(2024, 1, 15, 14, 30, tzinfo=tz)
# IANA Timezone
dt_bkk = datetime(2024, 1, 15, 14, 30, tzinfo=ZoneInfo('Asia/Bangkok'))
dt_utc = dt_bkk.astimezone(timezone.utc)
print(dt_bkk) # 2024-01-15 14:30:00+07:00
print(dt_utc) # 2024-01-15 07:30:00+00:00
Timedelta Operations
td = dt.timedelta(days=7, hours=3, minutes=30) print(td) # 7 days, 3:30:00 print(td.total_seconds()) # 617400.0 # Arithmetic future = dt.datetime.now() + dt.timedelta(days=30) past = dt.datetime.now() - dt.timedelta(weeks=2)
Best Practices
- ใช้
datetime.now(timezone.utc)แทนutcnow()(Deprecated 3.12) - เก็บ UTC ใน Database, แปลง Timezone ตอนแสดงผล
- ใช้
zoneinfo(3.9+) แทนpytz - Duration ใช้
timedelta, ไม่ใช่ Datetime Diff - Parsing:
fromisoformat()(3.7+) เร็วกว่าstrptime