python - 两个unix时间戳之间的差异

use*_*837 5 python-2.7

我有几个毫秒的时间戳,我想在几分钟内计算两者之间的差异:

d1 = 1502053449617 

current_time_utc = int(round(time.time() * 1000))
Run Code Online (Sandbox Code Playgroud)

d1的值由第三方API动态生成,并且采用UTC格式.我试图得到UTC和d1的当前时间之间的差异.

fmt = '%Y-%m-%d %H:%M:%S'

 time1  = datetime.strptime(d1, fmt)
 time2  = datetime.strptime(current_time_utc, fmt)
Run Code Online (Sandbox Code Playgroud)

我希望能够找到两者之间的差异(time1 - time2).如果我这样做,我得到一个错误说"字符串预期,长期给予"

print(    time1-time2)
Run Code Online (Sandbox Code Playgroud)

我希望两分钟之间的区别.请帮忙

Bur*_*lid 11

您不需要格式化字符串,只需要直接转换时间戳,首先将其除以1000.然后只需打印出差异(并以分钟计算):

from __future__ import division
import datetime

d1 = 1502053449617

converted_d1 = datetime.datetime.fromtimestamp(round(d1 / 1000))
current_time_utc = datetime.datetime.utcnow()

print((current_time_utc - converted_d1))
print((current_time_utc - converted_d1).total_seconds() / 60)
Run Code Online (Sandbox Code Playgroud)

以上打印:

3 days, 5:08:14.087515
4628.234791916667
Run Code Online (Sandbox Code Playgroud)


Gra*_*non 8

我必须计算两个 unix 时间戳之间的差异 - 但以天为单位,如下所示:

创建两个unix时间戳:

import datetime

timestamp1 = datetime.datetime(2017, 12, 1).strftime('%s')
timestamp2 = datetime.datetime(2017, 11, 14).strftime('%s')

print(timestamp1)
print(timestamp2)

1512079200
1510610400
Run Code Online (Sandbox Code Playgroud)

计算日差:

print((float(timestamp1)-float(timestamp2))/(60*60*24))
Run Code Online (Sandbox Code Playgroud)

输出:

17.0
Run Code Online (Sandbox Code Playgroud)