简体   繁体   English

在Java中将浮点时间戳从Python转换为Date

[英]Converting floating point timestamp from Python to Date in java

I have a Rest Service which receives a JSON object. 我有一个Rest服务,它接收JSON对象。 This JSON has a timestamp value in it. 此JSON中包含时间戳记值。 When I convert the JSON object to Java class I use a long variable (which I later use with new Date(long) to get a proper date object) for the timestamp. 当我将JSON对象转换为Java类时,我为时间戳使用了一个long变量(以后将它与new Date(long)以获得正确的date对象)。 Everything was working fine as the clients (in Java and JS) were sending timestamp as long. 当客户端(使用Java和JS)发送时间戳的时间很长时,一切工作正常。

Now we are adding a Python client to the service, and I am trying to send timestamp as long from Python. 现在,我们将Python客户端添加到服务中,并且我正尝试从Python发送时间戳。 But time.time() method in Python always gives a floating point number. 但是Python中的time.time()方法始终提供浮点数。 So I decided to use a double variable in my Rest Service's Java class and I am getting the timestamp correctly. 因此,我决定在Rest Service的Java类中使用一个double变量,并且正确获取了时间戳。 But then how do I convert this to a Date Object. 但是,然后我如何将其转换为Date对象。 Any ideas? 有任何想法吗?

So looking at the documentation (never used Python before) it looks like the time.time() method returns seconds since the epoch , while the Java Date object wants milliseconds from the epoch in its constructor. 因此,查看文档(以前从未使用过Python),看起来time.time()方法返回自epoch以来的秒数 ,而Java Date对象希望从其构造函数中的epoch毫秒起

So you need to do some fancy math to get the double into a long. 因此,您需要做一些花哨的数学运算才能使双精度数变长。 From the little bit of Python docs I just read, it seems like it would be easier to convert the seconds to milliseconds in the Python code and send the result as a long to the rest service. 从我刚刚阅读的少量Python文档中,似乎更容易将Python代码中的秒转换为毫秒并将结果作为较长的时间发送到rest服务。 Depending on how exact you have to be, you can just multiply the time.time() result by 1000 to get to milliseconds then round the rest to drop the floating point piece. 根据所需的精确度,您可以将time.time()结果乘以1000达到毫秒,然后舍入其余部分以除去浮点数。

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

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