3

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'
gene b.
  • 10,512
  • 21
  • 115
  • 227
  • Yep, such a shame different programming languages to this day cannot agree on a standard datetime representation, yet still call it "ISO format" – Arthur Khazbs Feb 11 '22 at 14:54

4 Answers4

3

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

ozerodb
  • 543
  • 3
  • 13
2

It fails because of the "Z" suffix at the end. If you replace it with "+00:00", you'll be in business.

Python 3.9.5 (default, May 24 2021, 12:50:35) 
[GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> def fromisoformat(s):
...   return datetime.fromisoformat(s.rstrip("Z") + "+00:00")
... 
>>> fromisoformat("2021-12-31T05:00:00.000Z")
datetime.datetime(2021, 12, 31, 5, 0, tzinfo=datetime.timezone.utc)
>>> 
Paul Bryan
  • 143
  • 7
1

As per documentation for fromisoformat(), it seems that 'Z' (which stands for UTC) is not recognised as a valid offset. Replacing it with +00:00 seems to work.

Other time zones would not be an issue as they are already automatically represented with a numerical offset. eg: +05:30 for IST.

1

The problem is the z at the end of your string.

from datetime import datetime

date = '2021-12-31T05:00:00.000'

t = datetime.fromisoformat(date)
print(t)
S.B
  • 13,077
  • 10
  • 22
  • 49