Search code examples
pythondatetimeiso8601

How would I convert this string '2022-07-07T10:30:00-07:00' into datetime obj in python?


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


Solution

  • 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'.