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
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