ใช้โมดูล datetime แปลง datetime เป็น UTC timestamp หากมี datetime object อยู่ใน UTC แล้ว ใช้ timestamp() ได้เลย คืนค่าเวลานับจาก epoch
หาก datetime อยู่ในเขตเวลาท้องถิ่น ให้แทนที่ timezone info ก่อน แล้วค่อยดึง timestamp
ตัวอย่าง (Python 3)
from datetime import datetime, timezone
dt = datetime(2015, 10, 19)
timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
print(timestamp)
ผลลัพธ์
1445212800.0
Python 2 ใช้ total_seconds() คำนวณจาก epoch (1 Jan 1970)
ตัวอย่าง (Python 2)
from datetime import datetime
dt = datetime(2015, 10, 19)
timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
print(timestamp)
ผลลัพธ์
1445212800.0