Converting dates to strings using Python

While working on converting ello.json to rss, I needed to convert the date formats, I needed to do it in Python and found the following code worked, using strptime and strfmtime. I had to augment the date string with the name of the day of the week attribute, so felt it had to via a date data type. (This is an important part of the requirement, since otherwise string manipulation would have been enough.) Finding exampes was hard, so I hope it helps,

Here’s the code

from datetime import datetime

def stripz(s):
	return s.strip('Z')

fmt='%Y-%m-%dT%H:%M:%S.%f'
ofmt='%a, %d %b %Y %H:%M:%S +0000' 

edate=stripz("2015-06-02T13:49:29.761Z") # shows the input format
dto=datetime.strptime(edate,fmt)
pubdate=datetime.strftime(dto, ofmt)

Dunno if I need to cope with the TZ as I did, which is to strip it out and write it as a constant but I am getting empty timezone data fields and strptime was barfing. pubdate is a string. This page in the python documentation helped.

This could almost certainly be done on one line and the function removed, but I find it easier to build this way and some COBOL habits are hard to drop.

Image Credit: @flickr ‘studio curve’ CC BY-NC-ND 2005

Related Posts

  • Python and datetime Links Here are some links http://docs.python.org/library/datetime.html, Official […]
  • Unicode in Python It's a very long time since I have had to deal with binary code translations, but when […]
  • Python I returned to Python in Oct 2010. I have two problems to solve, converting my […]
  • Date Differences in Excel I was looking to calculate if someone was under 27 years old; this can Be quite tricky […]
  • Planet Planet I started using Planet in about 2008 2006, it would seem? I rapidly came too "Planet […]

Leave a Reply

Your email address will not be published. Required fields are marked *