9

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

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

this is the best answer IMHO, because it is server agnostic.
@Alex T How about if I want to save datetime objects in django in the above JavaScript default format. It is more classic.
5

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.

Comments

0

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]

Comments

0

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!

1 Comment

I realized that this answer is EST specific, so what you need to do first is get rid of everything past the first "(" and then you can do away with the [:-3] in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.