Why does the following JS date string fail? It’s passed from a JS Date object to a Python backend.
JavaScript
x
5
1
2021-12-31T05:00:00.000Z
2
3
4
mydate = datetime.fromisoformat(form['expirationDate'])
5
Error:
JavaScript
1
2
1
ValueError: Invalid isoformat string: '2021-12-31T05:00:00.000Z'
2
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:
JavaScript
1
5
1
import dateutil.parser
2
mydate = dateutil.parser.isoparse('2021-12-31T05:00:00.000Z')
3
print(mydate)
4
5
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😅