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

ShadowRanger
  • 124,179
  • 11
  • 158
  • 228
  • 1
    You can use the [datetime.datetime.strptime](https://docs.python.org/3.6/library/datetime.html#datetime.datetime.strptime) method to convert strings to datetimes via a format string. – Kyle Oct 12 '17 at 17:50

2 Answers2

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())
y.luis
  • 1,712
  • 4
  • 23
  • 38
  • 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))` – Eugene Gr. Philippov Apr 30 '20 at 23:42
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'
adder
  • 3,302
  • 12
  • 26
  • 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))` – Eugene Gr. Philippov Apr 30 '20 at 23:42