简体   繁体   English

如何将 js 时间戳解码为 python 时间戳,反之亦然?

[英]How to decode js timestamp to python timestamp and vice versa?

I am making a request to one of server and getting response like this:我正在向其中一台服务器发出请求并得到如下响应:

result = {"object_type": "window_id", 
          "cctv_times" : ['1655375216687000', '1655375216717000', '1655375216717000', '1655375216775000']}

I am not able to understand the time format it is using and if I have to make a post request to that server with the current time, I am unable to convert the python timestamp into that format.我无法理解它使用的时间格式,如果我必须使用当前时间向该服务器发出发布请求,我无法将 python 时间戳转换为该格式。

In python, if I convert the current time into a timestamp, it looks like this:在 python 中,如果我将当前时间转换为时间戳,它看起来像这样:

from datetime import datetime

time_now = datetime.now().strftime("%s%f")

This gives me results in something like:这给了我类似的结果:

1655375242179881

But in server response, there are already a few zeros at the end even though the time is live from there, what is the format and how to convert python time into that format?但是在服务器响应中,即使时间从那里开始,最后也已经有几个零,格式是什么以及如何将 python 时间转换为该格式?

We know that datetime.now().strftime("%s%f") is a timestamps measured in microseconds (since %s is seconds and %f is microseconds).我们知道datetime.now().strftime("%s%f")是以微秒为单位测量的时间戳(因为%s是秒, %f是微秒)。

And 1655375216687000 and 1655375242179881 are the same length, which suggests your source data is also a timestamp measured in microseconds.并且16553752166870001655375242179881的长度相同,这表明您的源数据也是以微秒为单位的时间戳。 (The fact that the last three digits are always 000 suggests that it was originally derived from a source with milliseconds precision, but the value is clearly microseconds). (最后三位数字始终为000的事实表明它最初是从具有毫秒精度的源派生的,但该值显然是微秒)。

We can use datetime.fromtimestamp : https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp我们可以使用datetime.fromtimestamphttps ://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp

However this expects a time in seconds, "as returned by time.time() "但是,这需要以秒为单位的时间,“由time.time()返回”

So we can:所以我们可以:

from datetime import datetime

datetime.fromtimestamp(int('1655375216687000') / 1e6)

Which returns datetime.datetime(2022, 6, 16, 11, 26, 56, 687000)返回datetime.datetime(2022, 6, 16, 11, 26, 56, 687000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM