[python] 파이썬에서 두 datetime 객체의 시간 차이를 어떻게 알 수 있습니까?

datetime물체 의 시간 차이를 분 단위로 어떻게 알 수 있습니까?



답변

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> seconds_in_day = 24 * 60 * 60
datetime.timedelta(0, 8, 562000)
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

처음에서 나중에 시간을 빼면 difference = later_time - first_time차이 만있는 datetime 객체가 만들어집니다. 위의 예에서 0 분, 8 초 및 562000 마이크로 초입니다.


답변

Python 2.7의 새로운 기능은 timedelta인스턴스 메소드 .total_seconds()입니다. 파이썬 문서에서 이것은에 해당합니다 (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

참조 : http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds

>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds


답변

날짜 시간 예제 사용

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

년의 기간

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

일수

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

시간 내

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

분 단위

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

초 단위의 시간

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

마이크로 초 단위의 지속 시간

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

두 날짜 사이의 총 기간

>>> 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]))

또는 간단히 :

>>> print(now - then)

2019 수정
이 답변에 큰 관심을 끌기 때문에 일부 기능을 단순화 할 수있는 기능을 추가하겠습니다.

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


답변

하나만 빼면됩니다. timedelta차이 가있는 물체를 얻습니다 .

>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)

당신은 변환 할 수 있습니다 dd.days, dd.seconds그리고 dd.microseconds분.


답변

경우 a, b날짜 파이썬 3에서 그들 사이의 시간 차이를 찾기 위해 다음 오브젝트 있습니다 :

from datetime import timedelta

time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)

이전 파이썬 버전에서 :

time_difference_in_minutes = time_difference.total_seconds() / 60

경우 a, b에 의해 반환 순진 날짜는 객체입니다 datetime.now()개체가, UTC 오프셋 예 : 다른 주변 DST 전환 또는 과거 / 미래의 날짜 현지 시간을 나타내는 경우 잘못 될 수있다, 결과. 자세한 내용 : 날짜 시간 사이에 24 시간이 지 났는지 확인하십시오-Python .

안정적인 결과를 얻으려면 UTC 시간 또는 표준 시간대 인식 날짜 / 시간 개체를 사용하십시오.


답변

divmod를 사용하십시오.

now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past

d = divmod(now-then,86400)  # days
h = divmod(d[1],3600)  # hours
m = divmod(h[1],60)  # minutes
s = m[1]  # seconds

print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)


답변

이것은 두 개의 datetime.datetime 객체 사이에 경과 된 시간 수를 얻는 방법입니다.

before = datetime.datetime.now()
after  = datetime.datetime.now()
hours  = math.floor(((after - before).seconds) / 3600)