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

วิธีแปลงสตริง Python DateTime เป็นจำนวนเต็มมิลลิวินาที

ใช้โมดูล 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