1

(Python 3.5)

I have this string:

2021-05-05T13:13:56+00:00

I want to transform it to date object to perform latter actions on it.

I've tried the following:

d= "2021-05-05T13:13:56+00:00"
dt = datetime.strptime(d, '%Y-%m-%dT%H:%M:%S')

Which trows, as expected:

ValueError: unconverted data remains: +00:00

I do not know what are exactly these elements and, refering to this, I do not find what it could refer to.

How to convert this string as a date object ?

Itération 122442
  • 2,644
  • 2
  • 27
  • 73

1 Answers1

1

The extra value is %Z or UTC offset, which as MrFruppes pointed out, uses a colon after Python 3.7. You can add it to your strptime call, or use fromisoformat (which is more efficient).

from datetime import datetime

d = "2021-05-05T13:13:56+00:00"

dt = datetime.strptime(d, '%Y-%m-%dT%H:%M:%S%z')
dt_fromiso = datetime.fromisoformat(d)

print(dt)
print(dt_fromiso)
will-hedges
  • 1,254
  • 1
  • 9
  • 18
  • 2
    It must be added that `%z` parses a colon-separated UTC offset with Python version 3.7 onwards, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior). Please also note that for ISO format, you have [fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat). – FObersteiner May 06 '21 at 10:35
  • @MrFuppes thanks for educating me--I did not know that it had changed. I've updated my answer accordingly. – will-hedges May 06 '21 at 12:53
  • 1
    no worries; the reason why I'm so picky about this is that it gives you different datetime objects depending if you set `%z` vs. `+00:00` in the parsing directive - the first sets tzinfo to timezone.utc, the second leaves it as None. That can cause unexpected behaviour later on since Python treats naive datetime (tzinfo=None) as *local time*, not UTC. – FObersteiner May 06 '21 at 13:01
  • @MrFuppes I totally agree. It's much easier than manually passing a parse string to begin with, and now provides a more efficient solution – will-hedges May 06 '21 at 15:14
  • 1
    Thanks for the information. I am working with python 3.5.2, so I am not impacted. :) – Itération 122442 May 07 '21 at 12:12
  • 1
    @chemicalwill You may edit your answer to indicate the actual required code for <3.7 – Itération 122442 May 07 '21 at 12:13
  • @FlorianCastelain I will do that :) – will-hedges May 07 '21 at 13:31