简体   繁体   English

将 JavaScript date() 转换为 Python Django models.DateTimeField

[英]Convert JavaScript date() to Python Django models.DateTimeField

I using django model forms to submit data to the database.我使用 django 模型表单向数据库提交数据。 I use JavaScript to auto-fill the form with the following我使用 JavaScript 用以下内容自动填写表单

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此输出: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT)而 django 的模型。DateTimeField预计: 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我如何转换: Mon Feb 06 2017 11:39:05 GMT+0000 (GMT)2017-02-06 11:39谢谢

IMO, the best solution would be using unix timestamps , because you can avoid all complex stuff connected with timezones and time parsing. IMO,最好的解决方案是使用unix timestamps ,因为您可以避免所有与时区和时间解析相关的复杂内容。

JS: 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:

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.您应该考虑使用Moment.js ,它是操作日期和时区格式的最简单的 javascript 库。

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这是一个冗长的解决方案,但这应该可以将 Date 转换为 django 日期时间

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然后当我收到 API 调用时,我使用此命令将其转换

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!我建议保留时区,因为不同的服务器可能位于不同的时区,这可能会破坏您的日期!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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