Bora
Bora

Reputation: 1858

What java do to interpret unix timestamps?

I observed a behavior in java that I think a little bit different. If someone can shed light on my question I would be appreciated.

I have a project which uses MongoDB, Spring Data MongoDB at the backend. This is an android project.

When I insert a date field into a document in mongoDB, it is interpretted as ISODate in mongoDB. This gets converted by spring for me to java.util.Date. I have tried to convert this what I called to be a unix timestamp in this website, and it output some date in year 49311. I gave the timestamp as 1493967548032

In addition to that, when I tried to convert this timestamp to natural human readable format in python3.5, I get OSError which saying "Invalid argument".

timestamp = 1493967548032
datetime.datetime.fromtimestamp(timestamp)
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-35-a8b8548bb1ff> in <module>()
----> 1 datetime.datetime.fromtimestamp(timestamp)

OSError: [Errno 22] Invalid argument

However, java.util.Date data types have no problem with understanding the same thing with each other. And they interpret this timestamp as "2017-May-05". I need to understand how to interpret these java-style timestamps in python in order to test features in future.

I am on a Windows 10 x64 machine.

Upvotes: 0

Views: 194

Answers (2)

Andy Turner
Andy Turner

Reputation: 140318

Java's Date takes its parameter in milliseconds:

public Date(long date)

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Python's datetime.fromtimestamp takes its parameter in seconds.

classmethod datetime.fromtimestamp(timestamp[, tz])

Return the local date and time corresponding to the POSIX timestamp

(POSIX timestamps are in seconds)

So, simply divide your milliseconds by 1000:

>>> datetime.datetime.fromtimestamp(1493967548032 / 1000)
datetime.datetime(2017, 5, 5, 7, 59, 8)

If you want to keep the milliseconds, make sure you use float arithmetic:

>>> datetime.datetime.fromtimestamp((float) 1493967548032 / 1000)
datetime.datetime(2017, 5, 5, 7, 59, 8, 32000)

Upvotes: 2

divide this value 1493967548032 by thousand before converting to date, because the parameter's unit is seconds, not milliseconds.

That will produce:

>>> datetime.datetime.fromtimestamp(1493967548.032)
datetime.datetime(2017, 5, 5, 7, 59, 8, 32000)

Upvotes: 1

Related Questions