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
  • 143,180
  • 12
  • 188
  • 271
  • 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.rojo
  • 1,794
  • 4
  • 22
  • 41
  • 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,512
  • 1
  • 16
  • 28
  • 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