1

I'm writting a python app that convert YML files to static HTML pages for my blog (static site generator). I want to add an RSS feed. On a some place I read that the publication date must be:

<pubDate>Wed, 05 Jul 2017 18:38:23 GMT</pubDate>

But I have:

<pubDate>2017-07-05T18:38:23+00:00</pubDate>

The datetime API from Python is really cumbersome about these. How to convert the string 2017-07-05T18:38:23+00:00 to GMT?

Thanks in avanced.

junihh
  • 502
  • 1
  • 9
  • 25

3 Answers3

7
import datetime
basedate="2017-07-05T18:38:23+00:00"
formatfrom="%Y-%m-%dT%H:%M:%S+00:00"
formatto="%a %d %b %Y, %H:%M:%S GMT"
print datetime.datetime.strptime(basedate,formatfrom).strftime(formatto)

will return you the correct transcription : Wed 05 Jul 2017, 18:38:23 GMT

my source for the formats : http://strftime.org/

WNG
  • 3,705
  • 2
  • 22
  • 31
  • I would have used the time module (import time) instead of the datetime module but, I think the gist is the same. up vote. – Brad S. Aug 01 '17 at 21:49
5

While the other answers are correct, I always use arrow to deal with date time in python, it's very easy to use.

For you example, you can simply do

import arrow
utc = arrow.utcnow()
local = utc.to('US/Pacific')
local.format('YYYY-MM-DD HH:mm:ss ZZ')

The doc contains more information.

Salmaan P
  • 817
  • 1
  • 12
  • 32
1

I strongly suggest using dateutil which is a really powerful extension to datetime. It has a robust parser, that enables parsing any input format of datetime to a datetime object. Then you can reformat it to your desired output format.

This should answer your need:

from dateutil import parser

original_date = parser.parse("2017-07-05T18:38:23+00:00")
required_date = original_date.strftime("%a %d %b %Y, %H:%M:%S GMT")
Ori
  • 1,680
  • 21
  • 24
  • I get an error when I try with your code: "NameError: global name 'parser' is not defined". Something missed? – junihh Aug 02 '17 at 21:18
  • You are right. Sorry. I fixed the imports in my answer (`from dateutil import parser`). The rest stays the same – Ori Aug 03 '17 at 16:18