8

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()?

1
  • 1
    You can use the datetime.datetime.strptime method to convert strings to datetimes via a format string. Commented Oct 12, 2017 at 17:50

2 Answers 2

12

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())
Sign up to request clarification or add additional context in comments.

1 Comment

Ignoring timezone is wrong. 'Z' is a standard timezone for UTC +0. Try this: import pytz import datetime print(datetime.datetime.strptime('2020-02-03T14:33:22Z', '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.UTC))
6

You can use dateutil's parser:

>>> import dateutil.parser
>>> date = dateutil.parser.parse('2017-08-15T13:34:35Z', ignoretz=True)
>>> date
datetime.datetime(2017, 8, 15, 13, 34, 35)
>>> date.isoformat()
'2017-08-15T13:34:35'

1 Comment

Ignoring timezone is wrong. 'Z' is a standard timezone for UTC +0. Try this: import pytz import datetime print(datetime.datetime.strptime('2020-02-03T14:33:22Z', '%Y-%m-%dT%H:%M:%SZ').replace(tzinfo=pytz.UTC))