0

I am trying to convert the time below which i believe is ISO 8601 timestamp but i can't seem to convert.

time = '2021-04-06T23:51:50.514Z'

datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%SZ')

I get the error

ValueError: time data '2021-04-06T23:51:50.514Z' does not match format '%Y-%m-%dT%H:%M:%SZ'
meltedhead
  • 39
  • 7
  • 1
    Add a `.%f` between `S` and `Z`. Voting to close this question. – mechanical_meat Aug 25 '21 at 16:32
  • 1
    Your pattern accepts seconds but the value contains milliseconds. – Panagiotis Kanavos Aug 25 '21 at 16:33
  • 1
    It may be better to use `dateutil` instead of `strptime`. You'd only need `someDate = parser.parse(time)` – Panagiotis Kanavos Aug 25 '21 at 16:35
  • 1
    @PanagiotisKanavos if you can't parse such a straight forward string with the built-in functions then there's a glaring deficiency in the library. You shouldn't need an external package for something so simple. – Mark Ransom Aug 25 '21 at 16:39
  • 2
    @MarkRansom said every developer in every language. Java, C#, Python, Javascript. Which is why there are so many external libraries to cover the deficiencies of the languages. `Z` or `+00:00`? IANA timezones or abbreviations? `T` or ` ` ? – Panagiotis Kanavos Aug 25 '21 at 16:41
  • 1
    @PanagiotisKanavos for the general problem of dealing with the multitudes of ways people write dates, I agree - you need a complex library. But we're talking about an international standard that's tightly specified, it should be possible to handle it with the built-ins. Particularly in Python which prides itself on [There should be one-- and preferably only one --obvious way to do it.](https://www.python.org/dev/peps/pep-0020/) – Mark Ransom Aug 25 '21 at 17:59
  • 1
    @MarkRansom but `strptime` can't do it without someone providing the exact format. In C# for example I could use `DateTimeOffset.Parse()` to parse an ISO8601 string without specifying anything more. It would even handle `T` and `Z`, not just the offsets. Unfortunately, it doesn't understand IANA timezone names. – Panagiotis Kanavos Aug 25 '21 at 18:10
  • 1
    While you can use simple workarounds like [this](https://stackoverflow.com/a/62769371/10197418), going with @MarkRansom here, I'd really be interested why the 'Z' for UTC wasn't added to the `fromisoformat` method. Instead, it parses '+00:00' to UTC, which I'd consider kind of wrong; if I'm not mistaken, time zone Europe/London also has zero hours UTC offset if DST is off – FObersteiner Aug 25 '21 at 19:29

0 Answers0