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

Cách chuyển chuỗi timestamp UNIX sang ngày đọc được trong Python

Chuyển đổi UNIX timestamp (giây từ epoch) sang datetime readable dùng datetime.fromtimestamp() (local time) hoặc datetime.utcfromtimestamp() (UTC).

1. Chuyển 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

2. Chuyển sang datetime UTC (khuyến nghị)

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

3. Tạo datetime aware (có timezone) - Tốt nhất

from datetime import datetime, timezone

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

4. Xử lý timestamp mili-giây

ts_ms = 1500000000000
dt = datetime.fromtimestamp(ts_ms / 1000, tz=timezone.utc)
print(dt)

Tóm tắt

  • fromtimestamp(ts) → naive, local time.
  • utcfromtimestamp(ts) → naive, UTC.
  • fromtimestamp(ts, tz=timezone.utc) → aware UTC (khuyến nghị).
  • Mili-giây: chia 1000 trước.