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

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

问题描述:

我有两个以毫秒为单位的时间戳,我想以分钟为单位计算两者之间的差异:

I have two timestamps in miliseconds and i want to compute the difference between the two in minutes:

d1 = 1502053449617 

current_time_utc = int(round(time.time() * 1000))

d1 的值由第三方 API 动态生成,采用 UTC 格式.我正在尝试获取 UTC 和 d1 中的当前时间之间的差异.

The values for d1 are dynamically generated by a third party API and are in UTC . I am trying to get the difference between the current time in UTC and d1.

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

 time1  = datetime.strptime(d1, fmt)
 time2  = datetime.strptime(current_time_utc, fmt)

我希望能够找到两者之间的差异 (time1 - time2) .如果我执行以下操作,我会收到一条错误消息,提示预期的字符串,给出的时间很长"

I want to be able to find the difference between the two (time1 - time2) . If i do the below , i get an error saying "string expected, long given"

print(    time1-time2)

我想在几分钟内了解两者之间的差异.请帮忙

I want the difference between the two in minutes . Please help

字符串不需要格式化,直接转换时间戳,先除以1000,然后打印就好了找出差异(并在几分钟内计算出来):

You don't need to format the string, you just need to convert the timestamp directly, by first dividing it by 1000. Then its just a matter of printing out the differences (and calculating it in minutes):

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)

以上打印:

3 days, 5:08:14.087515
4628.234791916667