最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Convert JavaScript date() to Python Django models.DateTimeField - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Feb 6, 2017 at 11:48 simplyvicsimplyvic 2437 silver badges17 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

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.

You can set the pattern of date in your model form that accept particular format.

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!

发布评论

评论列表(0)

  1. 暂无评论