Search code examples
pythondateiso

Python parse string date


I have string like this:

2019-04-03 05:10:35+03:00

I need to output date like this:

2019-04-03 08:10:35

My code:

print(datetime.strptime(str("2019-04-03 05:10:35+03:00"), "%Y-%m-%d %H:%M:%S%z"))

but I have error:

ValueError: time data '2019-04-03 05:10:35+03:00' does not match format '%Y-%m-%d %H:%M:%S%z'


Solution

  • The problem is that your input string is improperly formatted. %z expects a string of format +HHMM or -HHMM; you have an extra :.

    Accordingly, you could use a regex to format it:

    import re
    
    source = '2019-04-03 05:10:35+03:00'
    formatted = re.sub(r'([+-])(\d\d):(\d\d)', r'\1\2\3', source)
    
    print(datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S%z").astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
    

    Output:

    2019-04-03 02:10:35