How to convert string to datetime?

user6611764 picture user6611764 · Oct 12, 2017 · Viewed 31.8k times · Source

I have the following string:

'2017-08-15T13:34:35Z'

How to convert this string to object that I can call .isoformat()?

someobject = convert('2017-08-15T13:34:35Z')
someobject.isoformat()

How to implement convert()?

Answer

y.luis picture y.luis · Oct 12, 2017

Here to parse a string to date time, then you can:

def convert(s):
    return datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')

someobject = convert('2017-08-15T13:34:35Z')
print(someobject.isoformat())