Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách chuyển timestamp string sang datetime object trong Python

UNIX timestamp là số giây (hoặc mili-giây) từ epoch UTC. Python chuyển ngược bằng datetime.fromtimestamp() (giờ địa phương) hoặc datetime.utcfromtimestamp() (giờ UTC).

1. Chuyển timestamp giây sang datetime địa phương

import datetime

ts = 1500000000
dt_local = datetime.datetime.fromtimestamp(ts)
print(dt_local.strftime('%Y-%m-%d %H:%M:%S'))
# Kết quả phụ thuộc múi giờ máy, ví dụ: 2017-07-14 08:10:00 (UTC+7)

2. Chuyển timestamp giây sang datetime UTC

dt_utc = datetime.datetime.utcfromtimestamp(ts)
print(dt_utc.strftime('%Y-%m-%d %H:%M:%S'))
# Kết quả: 2017-07-14 01:40:00 (luôn UTC)

3. Chuyển timestamp mili-giây

Chia 1000 trước khi truyền vào:

ts_ms = 1500000000000
dt = datetime.datetime.fromtimestamp(ts_ms / 1000)
print(dt)

4. Tạo datetime aware (có timezone) - Khuyến nghị

from datetime import datetime, timezone

ts = 1500000000
dt_utc = datetime.fromtimestamp(ts, tz=timezone.utc)
print(dt_utc)  # 2017-07-14 01:40:00+00:00
print(dt_utc.isoformat())  # 2017-07-14T01:40:00+00:00

Tóm tắt

  • fromtimestamp(ts) → datetime naive, giờ địa phương.
  • utcfromtimestamp(ts) → datetime naive, giờ UTC.
  • fromtimestamp(ts, tz=timezone.utc) → datetime aware UTC (tốt nhất).
  • Timestamp mili-giây: chia 1000 trước.