Dùng phương thức strftime() với các directive định dạng để trích xuất thành phần thời gian từ đối tượng datetime.
Các directive phổ biến cho thời gian
| Directive | Ý nghĩa | Ví dụ |
|---|---|---|
%H | Giờ 24h (00-23) | 14 |
%I | Giờ 12h (01-12) | 02 |
%M | Phút (00-59) | 30 |
%S | Giây (00-61) | 45 |
%f | Micro-giây (000000-999999) | 123456 |
%p | AM/PM | PM |
Ví dụ: Lấy MM:SS.microseconds
from datetime import datetime
now = datetime.now()
formatted = now.strftime('%M:%S.%f')
print(formatted)
# Kết quả: 31:15.093393
Ví dụ: Lấy từng thành phần riêng lẻ
now = datetime.now()
print("Phút:", now.strftime('%M')) # 31
print("Giây:", now.strftime('%S')) # 15
print("Micro-giây:", now.strftime('%f')) # 093393
print("Mili-giây:", now.strftime('%f')[:3]) # 093 (3 chữ số đầu)
Cách lấy dưới dạng số (int) - Hiệu quả hơn
now = datetime.now()
minute = now.minute
second = now.second
microsecond = now.microsecond
millisecond = now.microsecond // 1000
print(f"{minute}:{second:02d}.{millisecond:03d}")
Bảng đầy đủ các directive
Xem thêm: %a, %A, %b, %B, %c, %d, %j, %m, %U, %w, %W, %x, %X, %y, %Y, %Z, %% cho ngày, tuần, năm, timezone...