Hướng dẫn how do i calculate the time difference between two dates in python? - làm cách nào để tính chênh lệch thời gian giữa hai ngày trong python?

Sử dụng ví dụ DateTime

>>> from datetime import datetime
>>> then = datetime(2012, 3, 5, 23, 8, 15)        # Random date in the past
>>> now  = datetime.now()                         # Now
>>> duration = now - then                         # For build-in functions
>>> duration_in_s = duration.total_seconds()      # Total number of seconds between dates

Thời lượng tính bằng năm

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.

Thời lượng tính theo ngày

>>> days  = duration.days                         # Build-in datetime function
>>> days  = divmod(duration_in_s, 86400)[0]       # Seconds in a day = 86400

Thời lượng tính bằng giờ

>>> hours = divmod(duration_in_s, 3600)[0]        # Seconds in an hour = 3600

Thời lượng tính bằng phút

>>> minutes = divmod(duration_in_s, 60)[0]        # Seconds in a minute = 60

Thời lượng tính bằng giây

[!] Xem cảnh báo về việc sử dụng thời lượng tính bằng giây ở cuối bài đăng này

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

Thời lượng tính bằng micro giây

[!] Xem cảnh báo về việc sử dụng thời lượng tính bằng micro giây ở cuối bài đăng này

>>> microseconds = duration.microseconds          # Build-in datetime function

Tổng thời lượng giữa hai ngày

>>> 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 dates: %d days, %d hours, %d minutes and %d seconds" % (days[0], hours[0], minutes[0], seconds[0]))

hoặc đơn giản:

>>> print(now - then)

Chỉnh sửa năm 2019 Vì câu trả lời này đã đạt được lực kéo, tôi sẽ thêm một hàm, điều này có thể đơn giản hóa việc sử dụng cho một số Since this answer has gained traction, I'll add a function, which might simplify the usage for some

from datetime import datetime

def getDuration(then, now = datetime.now(), interval = "default"):

    # Returns a duration as specified by variable interval
    # Functions, except totalDuration, returns [quotient, remainder]

    duration = now - then # For build-in functions
    duration_in_s = duration.total_seconds() 
    
    def years():
      return divmod(duration_in_s, 31536000) # Seconds in a year=31536000.

    def days(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 86400) # Seconds in a day = 86400

    def hours(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 3600) # Seconds in an hour = 3600

    def minutes(seconds = None):
      return divmod(seconds if seconds != None else duration_in_s, 60) # Seconds in a minute = 60

    def seconds(seconds = None):
      if seconds != None:
        return divmod(seconds, 1)   
      return duration_in_s

    def totalDuration():
        y = years()
        d = days(y[1]) # Use remainder to calculate next variable
        h = hours(d[1])
        m = minutes(h[1])
        s = seconds(m[1])

        return "Time between dates: {} years, {} days, {} hours, {} minutes and {} seconds".format(int(y[0]), int(d[0]), int(h[0]), int(m[0]), int(s[0]))

    return {
        'years': int(years()[0]),
        'days': int(days()[0]),
        'hours': int(hours()[0]),
        'minutes': int(minutes()[0]),
        'seconds': int(seconds()),
        'default': totalDuration()
    }[interval]

# Example usage
then = datetime(2012, 3, 5, 23, 8, 15)
now = datetime.now()

print(getDuration(then)) # E.g. Time between dates: 7 years, 208 days, 21 hours, 19 minutes and 15 seconds
print(getDuration(then, now, 'years'))      # Prints duration in years
print(getDuration(then, now, 'days'))       #                    days
print(getDuration(then, now, 'hours'))      #                    hours
print(getDuration(then, now, 'minutes'))    #                    minutes
print(getDuration(then, now, 'seconds'))    #                    seconds

CẢNH BÁO: Hãy cẩn thận về tích hợp .seconds và .microseconds

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
2 và
>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
3 được giới hạn thành [0,86400) và [0,10^6).

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
2 and
>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
3 are capped to [0,86400) and [0,10^6) respectively.

Chúng nên được sử dụng cẩn thận nếu Timedelta lớn hơn giá trị trả về tối đa.

Examples:

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
4 là 1h và 200μs sau
>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
5:

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
0

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
4 là 1d và 1h sau
>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
5:

>>> years = divmod(duration_in_s, 31536000)[0]    # Seconds in a year=365*24*60*60 = 31536000.
1

Làm thế nào để tôi có được sự khác biệt về thời gian giữa hai ngày trong Python?

Phương thức TimeDelta (). Để tìm sự khác biệt giữa hai ngày trong Python, người ta có thể sử dụng lớp Timedelta có trong thư viện DateTime. Lớp Timedelta lưu trữ sự khác biệt giữa hai đối tượng DateTime.use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.

Làm thế nào để bạn tìm thấy sự khác biệt về thời gian giữa hai ngày?

Sử dụng hàm Datedif khi bạn muốn tính toán chênh lệch giữa hai ngày.Đầu tiên đặt ngày bắt đầu vào một ô và ngày kết thúc ở một ngày khác ...
Sử dụng Datedif để tìm tổng số năm.....
Sử dụng Datedif một lần nữa với các YM YM để tìm tháng.....
Sử dụng một công thức khác để tìm ngày ..

Bạn có thể trừ dấu thời gian trong Python không?

Để thêm hoặc trừ ngày, chúng tôi sử dụng một thứ gọi là hàm TimedelTa () có thể được tìm thấy trong lớp DateTime.Nó được sử dụng để thao tác ngày và chúng ta có thể thực hiện các hoạt động số học trên các ngày như thêm hoặc trừ.. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.

Làm thế nào để tôi tính toán sự khác biệt giữa hai ngày trong gấu trúc?

Sử dụng df.dates1-df.dates2 để tìm sự khác biệt giữa hai ngày và sau đó chuyển đổi kết quả trong hình thức tháng. dates1-df. dates2 to find the difference between the two dates and then convert the result in the form of months.