80

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.

Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288

2 Answers2

111

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
meshy
  • 8,470
  • 9
  • 51
  • 73
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
34

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.

Sumit
  • 2,190
  • 23
  • 31
  • 21
    Where is the time-zone qualifier (Z in this case)? – jtlz2 Nov 07 '17 at 11:39
  • it's not necessarily `Z` in this case. The datetime object in `date` is offset-naive so there shouldn't be any timezone qualifier at the end. – wpercy Feb 07 '19 at 19:36
  • you could make it aware like so `datetime.now(tz=timezone.utc).replace(microsecond=0).isoformat()` which would result with timezone of +00:00 which is equivalent to Z – Marc May 27 '21 at 01:48