0

I am having trouble converting this string '2022-07-07T10:30:00-07:00' to a datetime object in order to then extract the date and time separately.

I have tried the following code:

 date_time  =  '2022-07-07T10:30:00-07:00'
 d1 = datetime.strptime(date_time,"%Y-%m-%dT%H:%M:%S")

However,I get the following error:

ValueError: unconverted data remains: -07:00

thanks in advance

  • I think the problem is with the `07:00` at the end of your `date_time` variable. I'm not an expert in datetime zones format, but I guess `07:00` does not indicate anything. – TheFaultInOurStars Jul 11 '22 at 22:05
  • 2
    That's presumably supposed to be a timezone offset, but it's not formatted correctly. It should be `-0700`, and then you can use the `%Z` format to parse it. – Barmar Jul 11 '22 at 22:07
  • 2
    `%z` (lower case) will parse it, even with a colon, as of Python 3.7. There is a [note 6](https://docs.python.org/3/library/datetime.html?highlight=datetime%20strptime#technical-detail) – Mark Tolonen Jul 11 '22 at 22:18
  • Does this answer your question? [How to parse timezone with colon](https://stackoverflow.com/questions/30999230/how-to-parse-timezone-with-colon) – Pranav Hosangadi Jul 11 '22 at 22:23
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 12 '22 at 05:01

1 Answers1

1

The final -7:00 is a timezone offset in hours and minutes. %z can be used to parse it into a timezone-aware datetime object:

from datetime import datetime

date_time  =  '2022-07-07T10:30:00-07:00'
d1 = datetime.strptime(date_time,"%Y-%m-%dT%H:%M:%S%z")
print(repr(d1))
print(d1)

Output:

datetime.datetime(2022, 7, 7, 10, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200)))
2022-07-07 10:30:00-07:00

From the documentation:

Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251