10

I am newbie in Python and i m trying to do the following.

In PHP if we want to convert the date we use something like this:

$item_date  = date("Y-m-j G:i:s", strtotime($RSSitem->pubDate));

Now, i m trying to do the same using Python, but i cant understand the exact method for doing it.

Can anyone help me by writing this line to python?

zuperakos
  • 355
  • 4
  • 18

2 Answers2

18

According to RSS specification pubDate must follow RFC822:

mytime.strftime("%a, %d %b %Y %H:%M:%S %z")
Maksym Polshcha
  • 18,030
  • 8
  • 52
  • 77
  • I had better luck with time.strftime("%a, %d %b %Y %H:%M:%S %z", mytime) – Spike Williams Dec 13 '12 at 18:14
  • it is naive. `pubDate` in real rss feeds in the wild can use different time formats. Look at [the source of the `feedparser` module](https://github.com/kurtmckee/feedparser/blob/develop/feedparser/datetimes/__init__.py) that is referenced in my answer, to see how many time formats it has to handle. Unrelated: you could [use `email.utils.parsedate_tz/.mktime_tz` to parse rfc822 format](http://stackoverflow.com/a/23117071/4279). – jfs Sep 30 '15 at 00:08
5

There are two parts:

  • convert pubDate from string to a datetime/time object. If format for pubDate is fixed you could use datetime.strptime() function otherwise you could use dateutil.parser.parse() or feeparser._parse_date() (the later might be easier to install).
  • convert datetime/time object to string using .strftime() method/time.strftime() function.

See strftime() and strptime() behavior.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • This is the format of pubDate: Tue, 04 Sep 2012 20:20:18 GMT and i m trying to convert it to this: 04/09/2012 20:20 – zuperakos Sep 04 '12 at 20:27
  • @zuperakos: read the docs for strptime/strftime functions (see the link above). If you are stuck; update your question with the code that you have tried and its results. – jfs Sep 04 '12 at 20:30
  • Great! As i saw, feedparser._parse_date() returns this: time.struct_time(tm_year=2012, tm_mon=9, tm_mday=4, tm_hour=20, tm_min=20, tm_sec=18, tm_wday=1, tm_yday=248, tm_isdst=0). But how can i get only tm_year, tm_mon, tm_mday, tm_hour and tm_min and create a variable? – zuperakos Sep 04 '12 at 20:31
  • @zuperakos: call time.strftime() on the result to get the string – jfs Sep 04 '12 at 20:42
  • @zuperakos: don't put the code in a comment/answer. [update](http://stackoverflow.com/posts/12270531/edit) your question instead. – jfs Sep 04 '12 at 20:48