Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a date string into YYYYMMDD

Tags:

python

I've got a bunch of date strings in this form: -

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

I want them like this: -

YYYYMMDD

Currently I'm 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])

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

like image 632
martin blank Avatar asked Aug 04 '11 13:08

martin blank


1 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')

output:

20091130
20100331
20100930

or if you want to do it using 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')
like image 124
eumiro Avatar answered Sep 24 '22 00:09

eumiro