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

Cách chuyển datetime Python sang epoch bằng strftime

Có thể dùng directive %s trong strftime() để lấy giây từ epoch, nhưng cách này không chuẩn POSIX và có thể không hoạt động trên Windows. Khuyến nghị dùng timestamp() (Python 3.3+).

Cách 1: strftime('%s') - Không khuyến nghị

import datetime

dt = datetime.datetime(2017, 12, 1, 0, 0)
timestamp = dt.strftime('%s')
print(timestamp)  # 1445212800 (có thể sai trên Windows)

Cách 2: timestamp() - Chuẩn, khuyến nghị (Python 3.3+)

import datetime

dt = datetime.datetime(2017, 12, 1, 0, 0)
timestamp = dt.timestamp()
print(timestamp)  # 1445212800.0
print(int(timestamp))  # 1445212800

Cách 3: Tính thủ công (Python 2, cross-platform)

from datetime import datetime

dt = datetime(2017, 12, 1, 0, 0)
epoch = datetime(1970, 1, 1)
timestamp = (dt - epoch).total_seconds()
print(int(timestamp))  # 1445212800

⚠️ Lưu ý quan trọng

  • strftime('%s') hành vi phụ thuộc platform (thường dùng mktime → coi input là local time).
  • datetime.timestamp() coi naive datetime là local time. Muốn UTC: dt.replace(tzinfo=timezone.utc).timestamp().
  • Luôn ưu tiên timestamp() hoặc tính thủ công với epoch UTC rõ ràng.