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

Cách lấy phút, giây, mili-giây từ datetime.now() trong Python

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ĩaVí dụ
%HGiờ 24h (00-23)14
%IGiờ 12h (01-12)02
%MPhút (00-59)30
%SGiây (00-61)45
%fMicro-giây (000000-999999)123456
%pAM/PMPM

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...