[ Javascript date string to python datetime object ]

The current datetime is passed via an ajax request to a django backend where it will be stored in the database. To store it in the database, the date must first be converted to a datetime object which can be done for a date of the in UTC format (Eg. Sun, 04 Sep 2016 07:13:06 GMT) easily by the following statement:

>>> from datetime import datetime
>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT", "%a, %d %b %Y %H:%M:%S %Z")

However in such a method, there is no preservation of the user's timezone.

The javascript Date constructor call i.e. new Date() returns a date in the following format:

Sun Sep 04 2016 12:38:43 GMT+0530 (IST)

which gives an error when converting to datetime object.

>>> datetime.strptime("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)", "%a, %d %b %Y %H:%M:%S %Z")

ValueError: time data 'Sun Sep 04 2016 12:46:07 GMT+0530 (IST)' does not match format '%a, %d %b %Y %H:%M:%S %Z'

1) How to resolve this problem? 2) Is there any better way to approach it?

Answer 1


Your first problem is that the input has a different format. But unfortunatelly for you, that is not your only problem and it wouldn't work even if you fixed that.

The truth is that even the first format would fail with a different timezone:

datetime.strptime("Sun, 04 Sep 2016 07:13:06 IST", "%a, %d %b %Y %H:%M:%S %Z")

fails with:

ValueError: time data 'Sun, 04 Sep 2016 07:13:06 IST' does not match format '%a, %d %b %Y %H:%M:%S %Z'

strptime just isn't good enough for handling timezones.

Check these answers for your options:

Answer 2


You can use python's dateutil module to parse your date.

from dateutil import parser
parser.parse("Sun, 04 Sep 2016 07:13:06 GMT+0530 (IST)")

It gives the output as a datetime object:

datetime.datetime(2016, 9, 4, 7, 13, 6, tzinfo=tzoffset(u'IST', -19800))