Converting date from Python to Javascript
Question:
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?
Answers:
Javascript’s Date()
takes milliseconds as an argument. Python’s uses seconds. You have to multiply by 1,000.
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)
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 }});
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?
Javascript’s Date()
takes milliseconds as an argument. Python’s uses seconds. You have to multiply by 1,000.
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)
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 }});