萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 日期時間處理實用工具大全

Python 日期時間處理涉及 datetime、date、time、timestamp、struct_time、字串等多種表達。本文以 datetime 為核心,整理轉換關係圖與常用實用函數,涵蓋大多數業務場景。

核心物件關係圖


datetime  ←→  string (strftime/strptime)
   ↑  ↓
timestamp  ←→  struct_time (time.localtime/gmtime)
   ↑  ↓
   date

常用取值函數

import datetime, time, calendar

# 1. 當前 datetime
now = datetime.datetime.now()

# 2. 當天 date
today = datetime.date.today()

# 3. 明天 / N 天前後
tomorrow = today + datetime.timedelta(days=1)
three_days_ago = now - datetime.timedelta(days=3)

# 4. 當天起始/結束 (00:00:00 / 23:59:59.999999)
day_start = datetime.datetime.combine(today, datetime.time.min)
day_end   = datetime.datetime.combine(today, datetime.time.max)

# 5. 兩 datetime 差值 (秒數)
diff_sec = (datetime.datetime(2025,1,1) - now).total_seconds()

# 6. 本週最後一天 (週日)
sunday = today + datetime.timedelta(days=(6 - today.weekday()))

# 7. 本月最後一天
_, last_day = calendar.monthrange(today.year, today.month)
month_end = datetime.date(today.year, today.month, last_day)

# 8. 上月最後一天 (跨年安全)
first_this_month = datetime.date(today.year, today.month, 1)
last_month_end = first_this_month - datetime.timedelta(days=1)

格式化與解析 (字串 ⇄ datetime)

# datetime → string
now.strftime("%Y-%m-%d %H:%M:%S")   # '2025-01-15 14:30:00'

# string → datetime
dt = datetime.datetime.strptime("2024-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")

常用格式代碼

代碼含義範例
%Y四位年份2025
%m月份 01-1201
%d日期 01-3115
%H24小時 00-2314
%M分鐘 00-5930
%S秒數 00-5900
%f微秒 000000-999999123456
%z時區偏移+0800

時間戳轉換

# datetime → timestamp (float 秒)
ts = time.mktime(now.timetuple())          # 本地時間
ts = now.timestamp()                       # Python 3.3+, 感知時區

# timestamp → datetime
dt = datetime.datetime.fromtimestamp(ts)   # 本地時間
dt = datetime.datetime.utcfromtimestamp(ts) # UTC

struct_time 轉換

# datetime → struct_time
st = now.timetuple()

# struct_time → datetime (經由 timestamp)
ts = time.mktime(st)
dt = datetime.datetime.fromtimestamp(ts)

實務建議

  • 統一用 datetime:內部流轉以 datetime 為主,只在輸入/輸出 (API、DB、UI) 做轉換。
  • 時區處理:Python 3.9+ 使用 zoneinfo,舊版用 pytz;儲存統一用 UTC。
  • 避免字串運算:不要用字串拼接/切片做日期運算,務必轉為 datetime/date 後用 timedelta。
  • 效能:大量轉換時,datetime.strptime 較慢,可考慮 dateutil.parser.parse 或預編譯正則。

收藏此表,日期時間處理不再查文件。

copyright © 萬盛學電腦網 all rights reserved