Skip to content
Advertisement

Python datetime.fromisoformat() rejects JavaScript Date/Time string: ValueError: Invalid isoformat string

Why does the following JS date string fail? It’s passed from a JS Date object to a Python backend.

2021-12-31T05:00:00.000Z


mydate = datetime.fromisoformat(form['expirationDate'])

Error:

ValueError: Invalid isoformat string: '2021-12-31T05:00:00.000Z'

Advertisement

Answer

As per documentation, date.fromisoformat() only supports the YYYY-MM-DD format .

I believe the easiest way to solve the problem would be to use dateutil.parser.isoparse().

For example:

import dateutil.parser
mydate = dateutil.parser.isoparse('2021-12-31T05:00:00.000Z')
print(mydate)

will correctly print 2021-12-31 05:00:00+00:00

If you are bound to using datetime, take a look at strptime and/or this question

EDIT: my bad, I confused datetime with date, sooo.. as others pointed out you could remove the trailing Z and call it a day😅

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement