Convert date string to YYYYMMDD

I have a bunch of date strings in this form: -

30th November 2009 31st March 2010 30th September 2010 

I want them to be like this: -

 YYYYMMDD 

I am currently doing this: -

  parsed_date = "30th November 2009" part = parsed_date.split(' ') daymonth = part[0].strip(string.ascii_letters) mytime = daymonth+" "+part[1]+" "+part[2] time_format = "%d %B %Y" cdate = time.strptime(mytime, time_format) newdate = str(cdate[0])+str(cdate[1])+str(cdate[2]) 

This works, but I'm sure there is a better way ...

+8
python
source share
2 answers

Try dateutil :

 from dateutil import parser dates = ['30th November 2009', '31st March 2010', '30th September 2010'] for date in dates: print parser.parse(date).strftime('%Y%m%d') 

exit:

 20091130 20100331 20100930 

or if you want to do this using the standard datetime module:

 from datetime import datetime dates = ['30th November 2009', '31st March 2010', '30th September 2010'] for date in dates: part = date.split() print datetime.strptime('%s %s %s' % (part[0][:-2]), part[1], part[2]), '%d %B %Y').strftime('%Y%m%d') 
+10
source share

You can almost do this with a combination of strptime and strptime from the datetime module .

The problem is that the built-in formats support dates like 30 November 2010 , but not the 30th November 2010 . So, in the example below, I used the regex substitution to cross out the problematic characters. (The regular expression uses appearance to see if "st", "nd", "rd", or "th" precedes a digit, and if it replaces it with an empty string, thereby removing it from the string.)

 >>> import re >>> from datetime import datetime >>> mydate = "30th November 2009" >>> mydate = re.sub("(?<=\d)(st|nd|rd|th)","",mydate) >>> mydate '30 November 2009' >>> mydatetime = datetime.strptime(mydate,"%d %B %Y") >>> mydatetime datetime.datetime(2009, 11, 30, 0, 0) >>> mydatetime.strftime("%Y%M%d") '20090030' 
+5
source share

All Articles