Python查找两个时间戳之间的分钟差异

20

我该如何计算两个时间戳之间的分钟差。 例如:

timestamp1=2016-04-06 21:26:27
timestamp2=2016-04-07 09:06:02
difference = timestamp2-timestamp1
= 700 minutes (approx)
1个回答

33

使用 datetime 模块:

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2016-04-06 21:26:27', fmt)
tstamp2 = datetime.strptime('2016-04-07 09:06:02', fmt)

if tstamp1 > tstamp2:
    td = tstamp1 - tstamp2
else:
    td = tstamp2 - tstamp1
td_mins = int(round(td.total_seconds() / 60))

print('The difference is approx. %s minutes' % td_mins)

输出结果为:

The difference is approx. 700 minutes

td = tstamp1 - tstamp2 if tstamp1 > tstamp2 else tstamp2 - tstamp1 的一行代码 - Radio Controlled
3
如果您只想跳过if语句,可以这样写:td_mins = int(round(abs((tstamp1 - tstamp2).total_seconds()) / 60))。该代码用于计算两个时间戳之间的分钟数差异,并将结果四舍五入为整数。 - Kendall Trego

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接