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.
1 Answer
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'
>>>
2 Comments
mss tdy
I do get this error Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> t = datetime.datetime.fromisoformat(s) AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'
AKX
fromisoformat was added in Python 3.7. If you have an older Python, you'll need the iso8601 module's parse_date function: pypi.org/project/iso8601