![](/img/trans.png)
[英]How do I find the difference in milliseconds between two datetime objects in Python?
[英]How do I find the time difference between two datetime objects in python?
如何判斷兩個datetime
對象之間的時差(以分鍾為單位)?
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
datetime.timedelta(0, 8, 562000)
>>> seconds_in_day = 24 * 60 * 60
>>> divmod(difference.days * seconds_in_day + difference.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
從第一個時間difference = later_time - first_time
減去以后的時間difference = later_time - first_time
創建一個僅保留差異的日期時間對象。 在上面的示例中,它是 0 分 8 秒和 562000 微秒。
使用日期時間示例
>>> 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
警告:關於內置 .seconds 和 .microseconds 的警告
datetime.seconds
和datetime.microseconds
的上限分別為 [0,86400) 和 [0,10^6)。
如果 timedelta 大於最大返回值,則應謹慎使用它們。
例子:
end
是start
后 1 小時和 200 微秒:
>>> start = datetime(2020,12,31,22,0,0,500)
>>> end = datetime(2020,12,31,23,0,0,700)
>>> delta = end - start
>>> delta.microseconds
RESULT: 200
EXPECTED: 3600000200
end
是start
后的 1d 和 1h:
>>> start = datetime(2020,12,30,22,0,0)
>>> end = datetime(2020,12,31,23,0,0)
>>> delta = end - start
>>> delta.seconds
RESULT: 3600
EXPECTED: 90000
Python 2.7 的新功能是timedelta
實例方法.total_seconds()
。 從 Python 文檔中,這相當於(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
只需從另一個中減去一個。 您將獲得一個具有差異的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
是日期時間對象,那么在 Python 3 中找到它們之間的時差:
from datetime import timedelta
time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)
在早期的 Python 版本上:
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)
只是認為提及有關 timedelta 的格式可能會很有用。 strptime() 根據格式解析表示時間的字符串。
from datetime import datetime
datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'
time_dif = datetime.strptime(time1, datetimeFormat) - datetime.strptime(time2,datetimeFormat)
print(time_dif)
這將輸出:0:05:00.518000
只查找天數: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
我使用這樣的東西:
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
這將給出以秒為單位的差異(然后除以 60 得到分鍾):
import time
import datetime
t_start = datetime.datetime.now()
time.sleep(10)
t_end = datetime.datetime.now()
elapsedTime = (t_end - t_start )
print(elapsedTime.total_seconds())
輸出:
10.009222
這是我認為最簡單的方法,您無需擔心精度或溢出。
例如,使用elapsedTime.seconds
會損失很多精度(它返回一個整數)。 此外,正如這個答案指出的那樣, elapsedTime.microseconds
的上限為 10^6。 因此,例如,對於 10 秒的sleep()
, elapsedTime.microseconds
給出8325
(這是錯誤的,應該在10,000,000
左右)。
這是為了找出當前時間和上午 9.30 之間的差異
t=datetime.now()-datetime.now().replace(hour=9,minute=30)
要獲得hour
、 minute
和second
,您可以這樣做
>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m,s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60,m%60,s)
這是我使用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
以其他方式獲得日期之間的差異;
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)
所以在 Min 中獲得輸出。
謝謝
我已經使用持續集成測試的時間差異來檢查和改進我的功能。 如果有人需要,這里是簡單的代碼
from datetime import datetime
class TimeLogger:
time_cursor = None
def pin_time(self):
global time_cursor
time_cursor = datetime.now()
def log(self, text=None) -> float:
global time_cursor
if not time_cursor:
time_cursor = datetime.now()
now = datetime.now()
t_delta = now - time_cursor
seconds = t_delta.total_seconds()
result = str(now) + ' tl -----------> %.5f' % seconds
if text:
result += " " + text
print(result)
self.pin_time()
return seconds
time_logger = TimeLogger()
使用:
from .tests_time_logger import time_logger
class Tests(TestCase):
def test_workflow(self):
time_logger.pin_time()
... my functions here ...
time_logger.log()
... other function(s) ...
time_logger.log(text='Tests finished')
我在日志輸出中有類似的東西
2019-12-20 17:19:23.635297 tl -----------> 0.00007
2019-12-20 17:19:28.147656 tl -----------> 4.51234 Tests finished
基於@Attaque 很好的答案,我提出了一個更短的日期時間差計算器的簡化版本:
seconds_mapping = {
'y': 31536000,
'm': 2628002.88, # this is approximate, 365 / 12; use with caution
'w': 604800,
'd': 86400,
'h': 3600,
'min': 60,
's': 1,
'mil': 0.001,
}
def get_duration(d1, d2, interval, with_reminder=False):
if with_reminder:
return divmod((d2 - d1).total_seconds(), seconds_mapping[interval])
else:
return (d2 - d1).total_seconds() / seconds_mapping[interval]
我對其進行了更改以避免聲明重復函數,刪除了漂亮的打印默認間隔並增加了對毫秒、周和 ISO 月份的支持(請記住,月份只是近似值,基於每個月等於365/12
)。
其中產生:
d1 = datetime(2011, 3, 1, 1, 1, 1, 1000)
d2 = datetime(2011, 4, 1, 1, 1, 1, 2500)
print(get_duration(d1, d2, 'y', True)) # => (0.0, 2678400.0015)
print(get_duration(d1, d2, 'm', True)) # => (1.0, 50397.12149999989)
print(get_duration(d1, d2, 'w', True)) # => (4.0, 259200.00149999978)
print(get_duration(d1, d2, 'd', True)) # => (31.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'h', True)) # => (744.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'min', True)) # => (44640.0, 0.0014999997802078724)
print(get_duration(d1, d2, 's', True)) # => (2678400.0, 0.0014999997802078724)
print(get_duration(d1, d2, 'mil', True)) # => (2678400001.0, 0.0004999997244524721)
print(get_duration(d1, d2, 'y', False)) # => 0.08493150689687975
print(get_duration(d1, d2, 'm', False)) # => 1.019176965856293
print(get_duration(d1, d2, 'w', False)) # => 4.428571431051587
print(get_duration(d1, d2, 'd', False)) # => 31.00000001736111
print(get_duration(d1, d2, 'h', False)) # => 744.0000004166666
print(get_duration(d1, d2, 'min', False)) # => 44640.000024999994
print(get_duration(d1, d2, 's', False)) # => 2678400.0015
print(get_duration(d1, d2, 'mil', False)) # => 2678400001.4999995
您可能會發現這個快速片段在不太長的時間間隔內很有用:
from datetime import datetime as dttm
time_ago = dttm(2017, 3, 1, 1, 1, 1, 1348)
delta = dttm.now() - time_ago
days = delta.days # can be converted into years which complicates a bit…
hours, minutes, seconds = map(int, delta.__format__('').split('.')[0].split(' ')[-1].split(':'))
在 Python v.3.8.6 上測試
這是一個易於概括或轉化為函數且合理緊湊且易於遵循的答案。
ts_start=datetime(2020, 12, 1, 3, 9, 45)
ts_end=datetime.now()
ts_diff=ts_end-ts_start
secs=ts_diff.total_seconds()
days,secs=divmod(secs,secs_per_day:=60*60*24)
hrs,secs=divmod(secs,secs_per_hr:=60*60)
mins,secs=divmod(secs,secs_per_min:=60)
secs=round(secs, 2)
answer='Duration={} days, {} hrs, {} mins and {} secs'.format(int(days),int(hrs),int(mins),secs)
print(answer)
它以Duration=270 days, 10 hrs, 32 mins and 42.13 secs
形式給出答案
import datetime
date = datetime.date(1, 1, 1)
#combine a dummy date to the time
datetime1 = datetime.datetime.combine(date, start_time)
datetime2 = datetime.datetime.combine(date, stop_time)
#compute the difference
time_elapsed = datetime1 - datetime2
start_time --> 日期時間對象的開始時間
end_time--> datetime 對象的結束時間
我們不能直接減去 datetime.time 對象
因此我們需要為其添加一個隨機日期(我們使用組合)
或者您可以使用“今天”而不是 (1,1,1)
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.