Python在分钟内找到两个时间戳之间的差异

2024-04-19 06:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我怎么能在几分钟内找出两张时间戳的区别。 例如:

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

Tags: 时间区别minutesdifferenceapproxtimestamp2timestamp1
1条回答
网友
1楼 · 发布于 2024-04-19 06:18:25

使用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

相关问题 更多 >