Jay Jung
Jay Jung

Reputation: 1885

Within Django, how can I turn my Python datetime string into a Javascript Date object?

I am attempting to go from JSON data -> Javascript Date object within Django.

Currently, I have it set up so that I have a function which hits the API and saves the JSON data into one of my Model objects.
edit: the JSON datetime string looks like so: '2017-01-14 14:00:00'

Then in my View, I will query for the object containing the JSON, and send a datetime string which was acquired from the JSON, over to my template as a context variable.

Within the template, I am trying to graph the string data using Google Chart, and Google Charts requires that the first column for the Line graph to be a JS Date object. How can I turn the sent over template variable: {{ date }} into a format equivalent to Javascript's

new Date(2017, 01, 14)  

so that it may be used with Google Charts?

edit: The problem is not that I don't know how to format strings, but that I don't know how to get the string to appear in the first place, as it will be a django template variable first.

Upvotes: 1

Views: 4382

Answers (2)

Jay Jung
Jay Jung

Reputation: 1885

new Date({{ value|date:"U" }} * 1000)  

Converts Django template variable datetime object into a unix timestamp which is an acceptable argument for creating JS Date objects.
Multiply by 1000 to retrieve seconds value.

Upvotes: 5

Sam Dolan
Sam Dolan

Reputation: 32542

# general python datetime stringformatting:

>>> import datetime
>>> d = datetime.datetime.now()
>>> d.strftime("%Y-%m-%d %H:%M:%S")
'2017-01-14 05:04:26'

# you can embed other chars to fake the js date constructor
>>> d.strftime("new Date(%Y, %m, %d)")
'new Date(2017, 01, 14)'

See the docs @ https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Upvotes: 2

Related Questions