Python - Convert string representation of date to ISO 8601

PythonDatetimeIso8601

Python Problem Overview


In Python, how can I convert a string like this:

> Thu, 16 Dec 2010 12:14:05 +0000

to ISO 8601 format, while keeping the timezone?

Please note that the orginal date is string, and the output should be string too, not datetime or something like that.

I have no problem to use third parties libraries, though.

Python Solutions


Solution 1 - Python

Using dateutil:

import dateutil.parser as parser
text = 'Thu, 16 Dec 2010 12:14:05 +0000'
date = parser.parse(text)
print(date.isoformat())
# 2010-12-16T12:14:05+00:00

Solution 2 - Python

Python inbuilt datetime package has build in method to convert a datetime object to isoformat. Here is a example:

>>>from datetime import datetime
>>>date = datetime.strptime('Thu, 16 Dec 2010 12:14:05', '%a, %d %b %Y %H:%M:%S')
>>>date.isoformat()

output is

'2010-12-16T12:14:05'

I wrote this answer primarily for people, who work in UTC and doesn't need to worry about time-zones. You can strip off last 6 characters to get that string.

Python 2 doesn't have very good internal library support for timezones, for more details and solution you can refer to this answer on stackoverflow, which mentions usage of 3rd party libraries similar to accepted answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlon GubkinView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonSumitView Answer on Stackoverflow