Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Bài toán này thực sự rất phổ biến trong lập trình Python! Dưới đây là cách mà blog giải quyết nó:

Trước hết, chúng ta sử dụng thư viện datetime của Python để tính toán tổng số giây giữa hai thời điểm:

from datetime import datetime

first = datetime(2022, 3, 5, 23, 8, 15)
end = datetime(2023, 4, 5, 6, 8, 15)
duration = end - first
duration_in_s = duration.total_seconds()

Đoạn mã này sử dụng hàm divmod để tính khoảng thời gian theo các đơn vị. divmod, hay còn được biết đến là thuật toán chia lấy phần nguyên và phần dư, trả về kết quả với index 0 là phần nguyên và index 1 là phần dư.

# Year
years = divmod(duration_in_s, 31536000)[0]

# Days
days  = duration.days                         # Build-in datetime function
days  = divmod(duration_in_s, 86400)[0] 

# Hours
hours = divmod(duration_in_s, 3600)[0]  

# Minutes
minutes = divmod(duration_in_s, 60)[0]  

# Seconds
seconds = duration.seconds                    # Build-in datetime function
seconds = duration_in_s

# Microseconds
microseconds = duration.microseconds

Cuối cùng ta build một đoạn xử lý pha trộn giữa các cách lấy như sau:

days    = divmod(duration_in_s, 86400)        # Get days (without [0]!)
hours   = divmod(days[1], 3600)               # Use remainder of days to calc hours
minutes = divmod(hours[1], 60)                # Use remainder of hours to calc minutes
seconds = divmod(minutes[1], 1)               # Use remainder of minutes to calc seconds
print("Time between datetimes: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))

Kết quả:

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *