0

I do have a date and time format printed in '2020-05-06T15:16:24+05:30' which I would like to display in python in the format of YYYY-MMM-DD HH:MM:SS. Any pointers would be highly appreciated.

mss tdy
  • 15
  • 1
  • 9
  • Does this answer your question? [Parse date string and change format](https://stackoverflow.com/questions/2265357/parse-date-string-and-change-format) – mkrieger1 May 06 '20 at 09:58

1 Answers1

1

You have an ISO8601 datetime; yse the datetime module to parse a datetime object out of it, then format as required.

Note the timezone information is "hidden" in your desired formatting, but exists in that tzinfo property.

>>> s = '2020-05-06T15:16:24+05:30'
>>> import datetime
>>> t = datetime.datetime.fromisoformat(s)
datetime.datetime(2020, 5, 6, 15, 16, 24, tzinfo=datetime.timezone(datetime.timedelta(seconds=19800)))
>>> t.strftime("%Y-%m-%d %H:%M:%S")
'2020-05-06 15:16:24'
>>>
AKX
  • 93,995
  • 11
  • 81
  • 98
  • I do get this error Traceback (most recent call last): File "", line 1, in t = datetime.datetime.fromisoformat(s) AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat' – mss tdy May 06 '20 at 10:11
  • `fromisoformat` was added in Python 3.7. If you have an older Python, you'll need the iso8601 module's `parse_date` function: https://pypi.org/project/iso8601/ – AKX May 06 '20 at 10:31