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

Cách chuyển chuỗi datetime Python sang mili-giây nguyên

Chuyển đổi datetime string sang timestamp UNIX mili-giây (integer) bao gồm 2 bước: parse string thành datetime, rồi chuyển sang mili-giây.

1. Lấy thời gian hiện tại (mili-giây)

import time
ms = int(round(time.time() * 1000))
print(ms)  # 1514825676008

2. Chuyển datetime object sang mili-giây

Python 3.3+: dùng datetime.timestamp()

from datetime import datetime

dt = datetime(2018, 1, 1)
ms = int(round(dt.timestamp() * 1000))
print(ms)  # 1514745000000

3. Chuyển datetime STRING sang mili-giây

from datetime import datetime

date_str = "2018-01-01 12:30:45"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
ms = int(round(dt.timestamp() * 1000))
print(ms)

⚠️ Cảnh báo về múi giờ

datetime.timestamp() coi datetime naive là giờ địa phương. Để kết quả nhất quán cross-platform:

from datetime import datetime, timezone

# Cách an toàn: gán UTC rõ ràng
dt = datetime(2018, 1, 1, tzinfo=timezone.utc)
ms = int(round(dt.timestamp() * 1000))

Python 2

from datetime import datetime
dt = datetime(2018, 1, 1)
ms = int((dt - datetime(1970, 1, 1)).total_seconds() * 1000)