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

Chuyển Python date sang Unix timestamp

Dùng datetime module convert datetime → UTC timestamp.

Python 3: timestamp() method

from datetime import datetime, timezone

dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)  # 1445212800.0

Nếu datetime đã là UTC: dt.timestamp() trực tiếp.

Python 2: total_seconds()

from datetime import datetime

dt = datetime(2015, 10, 19)
epoch = datetime(1970, 1, 1)
timestamp = (dt - epoch).total_seconds()
print(timestamp)  # 1445212800.0

Lưu ý: Naive datetime (không tzinfo) được coi là local time khi gọi timestamp(). Luôn explicit timezone.