如何找到python中两个datetime对象之间的时间差?

时间:2022-05-26 16:40:11

How do I tell the time difference in minutes between two datetime objects?

我如何区分两个datetime对象之间的时间差异?

12 个解决方案

#1


207  

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 86400 + c.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

#2


99  

New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

Python 2.7的新版本是timedelta实例方法。total_seconds()。从Python文档中,这相当于(td)。微秒+(td。秒+道明。天数* 24 * 3600)* 10**6)/ 10**6。

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

参考: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

#3


19  

Just subtract one from the other. You get a timedelta object with the difference.

从另一个中减去一个。你会得到一个有差异的时间增量对象。

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

You can convert dd.days, dd.seconds and dd.microseconds to minutes.

您可以转换dd.days, dd.seconds和dd.microseconds to minutes。

#4


15  

Use divmod:

使用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)

#5


15  

If a, b are datetime objects then to find the time difference between them in Python 3:

如果a, b是datetime对象,那么在Python 3中找到它们之间的时间差:

from datetime import timedelta

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

On earlier Python versions:

早的Python版本:

time_difference_in_minutes = time_difference.total_seconds() / 60

If a, b are naive datetime objects such as returned by datetime.now() then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: Find if 24 hrs have passed between datetimes - Python.

如果a、b是天真的datetime对象,如datetime.now(),那么如果对象以不同的UTC偏移量(如DST转换或过去/未来日期)表示本地时间,那么结果可能是错误的。更多细节:查找24小时是否已经在datetimes - Python之间传递。

To get reliable results, use UTC time or timezone-aware datetime objects.

为了得到可靠的结果,使用UTC时间或timezone-aware datetime对象。

#6


6  

This is how I get the number of hours that elapsed between two datetime.datetime objects:

这就是我如何得到在两个datetime之间经过的小时数。datetime对象:

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

#7


4  

To just find the number of days: timedelta has a 'days' attribute. You can simply query that.

只需找到天数:timedelta具有“天数”属性。您可以简单地查询它。

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

#8


2  

Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.

只是认为在timedelta中提到格式也很有用。strptime()根据格式解析表示时间的字符串。

import datetime
from datetime import timedelta

datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'    
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'  
timedelta = datetime.datetime.strptime(time1, datetimeFormat) - datetime.datetime.strptime(time2,datetimeFormat)

This will output: 0:05:00.518000

这将输出:0:05:00.518000

#9


1  

Using datetime example

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

Duration in years

多年来持续时间

>>> years = divmod(duration_in_s, 31556926)[0]    # Seconds in a year=31556926.

Duration in days

时间在天

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

Duration in hours

时间在小时

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

Duration in minutes

时间在几分钟内

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

Duration in seconds

时间以秒为单位

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

Duration in microseconds

时间以微秒为单位

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

Total duration between the two dates

两个日期之间的总持续时间。

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

or simply:

或者仅仅是:

>>> print(now - then)

#10


0  

This is my approach using mktime.

这是我使用mktime的方法。

from datetime import datetime, timedelta
from time import mktime

yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()

difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60

#11


0  

In Other ways to get difference between date;

以其他方式来区分日期;

import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

So get output in Min.

因此,在最小值中得到输出。

Thanks

谢谢

#12


0  

I use somethign like this :

我用这样的东西:

from datetime import datetime

def check_time_difference(t1: datetime, t2: datetime):
    t1_date = datetime(
        t1.year,
        t1.month,
        t1.day,
        t1.hour,
        t1.minute,
        t1.second)

    t2_date = datetime(
        t2.year,
        t2.month,
        t2.day,
        t2.hour,
        t2.minute,
        t2.second)

    t_elapsed = t1_date - t2_date

    return t_elapsed

# usage 
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)

print(elapsed_time)
#return : 0:08:52

#1


207  

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 86400 + c.seconds, 60)
(0, 8)      # 0 minutes, 8 seconds

#2


99  

New at Python 2.7 is the timedelta instance method .total_seconds(). From the Python docs, this is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6.

Python 2.7的新版本是timedelta实例方法。total_seconds()。从Python文档中,这相当于(td)。微秒+(td。秒+道明。天数* 24 * 3600)* 10**6)/ 10**6。

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

参考: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

#3


19  

Just subtract one from the other. You get a timedelta object with the difference.

从另一个中减去一个。你会得到一个有差异的时间增量对象。

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

You can convert dd.days, dd.seconds and dd.microseconds to minutes.

您可以转换dd.days, dd.seconds和dd.microseconds to minutes。

#4


15  

Use divmod:

使用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)

#5


15  

If a, b are datetime objects then to find the time difference between them in Python 3:

如果a, b是datetime对象,那么在Python 3中找到它们之间的时间差:

from datetime import timedelta

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

On earlier Python versions:

早的Python版本:

time_difference_in_minutes = time_difference.total_seconds() / 60

If a, b are naive datetime objects such as returned by datetime.now() then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: Find if 24 hrs have passed between datetimes - Python.

如果a、b是天真的datetime对象,如datetime.now(),那么如果对象以不同的UTC偏移量(如DST转换或过去/未来日期)表示本地时间,那么结果可能是错误的。更多细节:查找24小时是否已经在datetimes - Python之间传递。

To get reliable results, use UTC time or timezone-aware datetime objects.

为了得到可靠的结果,使用UTC时间或timezone-aware datetime对象。

#6


6  

This is how I get the number of hours that elapsed between two datetime.datetime objects:

这就是我如何得到在两个datetime之间经过的小时数。datetime对象:

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

#7


4  

To just find the number of days: timedelta has a 'days' attribute. You can simply query that.

只需找到天数:timedelta具有“天数”属性。您可以简单地查询它。

>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13

#8


2  

Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.

只是认为在timedelta中提到格式也很有用。strptime()根据格式解析表示时间的字符串。

import datetime
from datetime import timedelta

datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'    
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'  
timedelta = datetime.datetime.strptime(time1, datetimeFormat) - datetime.datetime.strptime(time2,datetimeFormat)

This will output: 0:05:00.518000

这将输出:0:05:00.518000

#9


1  

Using datetime example

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

Duration in years

多年来持续时间

>>> years = divmod(duration_in_s, 31556926)[0]    # Seconds in a year=31556926.

Duration in days

时间在天

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

Duration in hours

时间在小时

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

Duration in minutes

时间在几分钟内

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

Duration in seconds

时间以秒为单位

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

Duration in microseconds

时间以微秒为单位

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

Total duration between the two dates

两个日期之间的总持续时间。

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

or simply:

或者仅仅是:

>>> print(now - then)

#10


0  

This is my approach using mktime.

这是我使用mktime的方法。

from datetime import datetime, timedelta
from time import mktime

yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()

difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60

#11


0  

In Other ways to get difference between date;

以其他方式来区分日期;

import dateutil.parser
import datetime
last_sent_date = "" # date string
timeDifference = current_date - dateutil.parser.parse(last_sent_date)
time_difference_in_minutes = (int(timeDifference.days) * 24 * 60) + int((timeDifference.seconds) / 60)

So get output in Min.

因此,在最小值中得到输出。

Thanks

谢谢

#12


0  

I use somethign like this :

我用这样的东西:

from datetime import datetime

def check_time_difference(t1: datetime, t2: datetime):
    t1_date = datetime(
        t1.year,
        t1.month,
        t1.day,
        t1.hour,
        t1.minute,
        t1.second)

    t2_date = datetime(
        t2.year,
        t2.month,
        t2.day,
        t2.hour,
        t2.minute,
        t2.second)

    t_elapsed = t1_date - t2_date

    return t_elapsed

# usage 
f = "%Y-%m-%d %H:%M:%S+01:00"
t1 = datetime.strptime("2018-03-07 22:56:57+01:00", f)
t2 = datetime.strptime("2018-03-07 22:48:05+01:00", f)
elapsed_time = check_time_difference(t1, t2)

print(elapsed_time)
#return : 0:08:52