Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript date() to Python Django models.DateTimeField

I using django model forms to submit data to the database. I use JavaScript to auto-fill the form with the following

document.getElementById('id_date_received').value = Date();

This outputs: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) while django's models.DateTimeField expects: 2017-02-06 11:39

How do i convert: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT) to 2017-02-06 11:39 Thanks

like image 826
simplyvic Avatar asked Feb 06 '17 11:02

simplyvic


2 Answers

IMO, the best solution would be using unix timestamps, because you can avoid all complex stuff connected with timezones and time parsing.

JS:

js_date = new Date('2012.08.10');

// getTime() returns milliseconds from the UNIX epoch,
// so divide it by 1000 to get the seconds representation.

js_timestamp = js_date.getTime() / 1000;

Python:

python_date = datetime.datetime.fromtimestamp(js_timestamp)
like image 88
Alex T Avatar answered Oct 21 '22 23:10

Alex T


You should consider use Moment.js, it's the easiest javascript library to manipulate dates and timezone formats.

So the code would by something like this:

moment(YOUR_DATE_VARIABLE).format('YYYY-MM-DD HH:mm'); // 2017-02-06 11:39

Hope this help you.

like image 31
Dobbin Avatar answered Oct 22 '22 00:10

Dobbin