Posted by admin on

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


This site uses Akismet to reduce spam. Learn how your comment data is processed.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close