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)
>>> 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
>>> 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
< p > # EYZ0 datetime.seconds和datetime.microseconds的上限分别为[0,86400)和[0,10^6).
如果timedelta大于返回值的最大值,则应该谨慎使用。
例子:
end为start后1h和200μs:
>>> 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
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')
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(':'))
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
< p > start_time——比;datetime对象 的起始时间
end_time——比;datetime对象 的结束时间