简体   繁体   中英

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

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)

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.

您可以在接受特定格式的模型表单中设置日期模式。

input_formats=[list of datetime patterns that you want to accept]

This is a bit of a long-winded solution but this should work to convert Date to django date time

I first convert the Date to a string by cast

(String(date_var))

then when I receive the API call I convert it using this command

datetime.datetime.strptime(",".join(original_time[:original_time.find("(")-1].split(" ")).replace("GMT",""), '%a,%B,%d,%Y,%H:%M:%S,%z')

I would recommend preserving the timezone as different servers can be in different timezones which can screw up your dates!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM