33

I'm having difficulty working with dates in Python and Javascript.

>>> d = date(2004, 01, 01)
>>> d
datetime.date(2004, 1, 1)
>>> time.mktime(d.timetuple())
1072944000.0

Then, in Javascript (data sent over Ajax):

>>> new Date(1072944000.0)
Tue Jan 13 1970 02:02:24 GMT-0800 (PST) {}

I'm confused. Shouldn't the Javascript date be the same as the one that I entered in Python? What am I doing wrong?

3 Answers 3

54

Javascript's Date() takes milliseconds as an argument. Python's uses seconds. You have to multiply by 1,000.

Sign up to request clarification or add additional context in comments.

Comments

26

Python:

import datetime, time
d = datetime.datetime.utcnow()
for_js = int(time.mktime(d.timetuple())) * 1000

Then in JS:

new Date({{ for_js }});

In Flask you can do:

@app.template_filter('date_to_millis')
def date_to_millis(d):
    """Converts a datetime object to the number of milliseconds since the unix epoch."""
    return int(time.mktime(d.timetuple())) * 1000

And then do:

new Date({{ current_user.created|date_to_millis }});

Comments

13

Python is returning the time since the epoch in seconds. Javascript takes the time in milliseconds. Multiply the time by 1000 before passing it to Date() and you should get the expected result.

new Date(1072944000.0 * 1000)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.