Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลงสตริง datetime เป็น timestamp มิลลิวินาที UNIX

ดึงเวลาปัจจุบันเป็นมิลลิวินาทีด้วยโมดูล time ใช้ time.time() ได้วินาที (float) คูณ 1000 แล้วปัดเศษ

ตัวอย่าง

import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)

ผลลัพธ์

1514825676008

หากต้องการแปลงอ็อบเจกต์ datetime ให้เป็น timestamp มิลลิวินาที ใช้เมธอด timestamp() แล้วคูณ 1000 ปัดเศษ

ตัวอย่าง

import time
from datetime import datetime

dt = datetime(2018, 1, 1)
milliseconds = int(round(dt.timestamp() * 1000))
print(milliseconds)

ผลลัพธ์

1514745000000