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

Basic Date and Time Types ใน Python (โมดูล datetime)

โมดูล datetime ให้ Classes สำหรับจัดการ Date/Time: date, time, datetime, timedelta, tzinfo, timezone

import datetime


Class Overview

ClassAttributesคำอธิบาย
dateyear, month, dayวันที่อย่างเดียว (Gregorian Calendar)
timehour, minute, second, microsecond, tzinfoเวลาอย่างเดียว (ไม่ผูกวันที่)
datetimedate + time attributesวันที่และเวลารวมกัน
timedeltadays, seconds, microsecondsความต่างระหว่าง Date/Time
tzinfoAbstract Base ClassTimezone Info
timezoneFixed Offset from UTCConcrete tzinfo (3.2+)

Constants

  • datetime.MINYEAR = 1
  • datetime.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ความหมายตัวอย่าง
%YYear (4 digits)2024
%mMonth (01-12)01
%dDay (01-31)05
%HHour 24h (00-23)14
%IHour 12h (01-12)02
%MMinute (00-59)30
%SSecond (00-59)59
%fMicrosecond (000000-999999)123456
%AWeekday FullSunday
%aWeekday AbbrevSun
%BMonth FullJanuary
%bMonth AbbrevJan
%zUTC Offset+0700
%ZTimezone NameICT
%cLocale Date/TimeSun Jan 5 14:30:59 2024
%xLocale Date01/05/24
%XLocale Time14: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