如何在两个datetime对象之间以分钟为单位区分时间?
当前回答
使用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为例
>>> 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。微秒的上限分别为[0,86400)和[0,10^6)。
如果timedelta大于返回值的最大值,则应该谨慎使用。
例子:
开始后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在开始后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
如果a, b是datetime对象,那么在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对象,例如datetime.now()返回的,那么如果对象表示具有不同UTC偏移量的本地时间,例如DST转换前后或过去/未来日期,则结果可能是错误的。更多细节:查找datetimes之间是否已经过了24小时- Python。
要获得可靠的结果,请使用UTC时间或时区感知的datetime对象。
这就是我如何获得两个datetime之间经过的小时数。datetime对象:
before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
只要用一个减去另一个。你会得到一个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 = d2 - d1
>>> print (dd.days) # get days
>>> print (dd.seconds) # get seconds
>>> print (dd.microseconds) # get microseconds
>>> print (int(round(dd.total_seconds()/60, 0))) # get minutes
这可能会帮助一些人,用这个方法找到过期与否其计算天数。这是dt。秒和dt。微秒也可用
from datetime import datetime
# updated_at = "2022-10-20T07:18:56.950563"
def is_expired(updated_at):
expires_in = 7 #days
datetime_format = '%Y-%m-%dT%H:%M:%S.%f'
time_difference = datetime.now() - datetime.strptime(updated_at, datetime_format)
return True if time_difference.days > expires_in else False
推荐文章
- Python glob多个文件类型
- 如何可靠地打开与当前运行脚本在同一目录下的文件
- Python csv字符串到数组
- 如何在Python中进行热编码?
- 如何嵌入HTML到IPython输出?
- 在Python生成器上使用“send”函数的目的是什么?
- 是否可以将已编译的.pyc文件反编译为.py文件?
- Django模型表单对象的自动创建日期
- 在Python中包装长行
- 如何计算两个时间串之间的时间间隔
- 为什么在JavaScript的Date构造函数中month参数的范围从0到11 ?
- 在Windows批处理脚本中格式化日期和时间
- 我如何才能找到一个Python函数的参数的数量?
- 您可以使用生成器函数来做什么?
- 将Python诗歌与Docker集成