Python|使用 datetime.timedelta() 方法的两个日期之间的差异(以分钟为单位)
要在Python中找出两个日期之间的差异,可以使用datetime库中的timedelta类。 timedelta 类存储两个日期时间对象之间的差异。
要以分钟的形式找出两个日期之间的差异,可以使用 timedelta 对象的属性seconds可以进一步除以 60 以转换为分钟。
示例 1:
以下程序采用两个 datetime 对象并以分钟为单位找出它们之间的差异。
import datetime
# datetime(year, month, day, hour, minute, second)
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
# returns a timedelta object
c = a-b
print('Difference: ', c)
minutes = c.total_seconds() / 60
print('Total difference in minutes: ', minutes)
# returns the difference of the time of the day
minutes = c.seconds / 60
print('Difference in minutes: ', minutes)
输出:
Difference: 36 days, 10:04:20
Difference in minutes: 604.3333333333334
示例 2:
要获得更合适的答案,可以使用 divmod() 以秒为单位返回分钟的小数部分:
import datetime
# datetime(year, month, day, hour, minute, second)
a = datetime.datetime(2017, 6, 21, 18, 25, 30)
b = datetime.datetime(2017, 5, 16, 8, 21, 10)
# returns a timedelta object
c = a-b
print('Difference: ', c)
# returns (minutes, seconds)
minutes = divmod(c.total_seconds(), 60)
print('Total difference in minutes: ', minutes[0], 'minutes',
minutes[1], 'seconds')
# returns the difference of the time of the day (minutes, seconds)
minutes = divmod(c.seconds, 60)
print('Total difference in minutes: ', minutes[0], 'minutes',
minutes[1], 'seconds')
输出:
Difference: 36 days, 10:04:20
Difference in minutes: 604 minutes 20 seconds