Lucas Veiga
Lucas Veiga

Reputation: 197

How to convert date with suffix to another format in python

I need to convert something like:

Mar 31st, 2014
Aug 13th, 2014
Sep 2nd, 2014

Into:

31/03/2014
13/08/2014
2/09/2014

I've been looking at strptime but the suffixes are getting in the way. Thank you.

Upvotes: 1

Views: 2106

Answers (4)

Kannan Mohan
Kannan Mohan

Reputation: 1840

I would use the below approach.

import datetime
import re

# Collect all dates into a list.
dates = [ 'Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014' ]

# Compile a pattern to replace alpha digits in date to empty string.
pattern = re.compile('(st|nd|rd|th|,)')

# Itegrate through the list and replace the old format to the new one.
for offset, date in enumerate(dates):
    date = pattern.sub('', date)
    date = datetime.datetime.strptime(date, '%b %d %Y')
    dates[offset] = str(date.day) + '/' + str(date.month) + '/' + str(date.year)
    print(dates[offset]);

Upvotes: 0

Ivan Klass
Ivan Klass

Reputation: 6627

The main problem with using standard python modules that there are no format option for days with suffixes (I mean 'st', 'nd', 'th'..), and no option for day without leading zeros. As for suffixes, you can delete them safely, cause they don't appear in month names. As for day without leading zeros, we can construct string from explicitly selecting date parts.

from datetime import datetime 

def convert(dt_string, in_format='%b %d, %Y', out_format='{0.day}{0:/%m/%Y}'):
    for suffix in ('st', 'nd', 'rd', 'th'):
        dt_string = dt_string.replace(suffix, '')
    return out_format.format(datetime.strptime(dt_string, in_format))


dates = ['Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014']
print map(convert, dates)

Upvotes: 1

Weafs.py
Weafs.py

Reputation: 22992

You could define your own function to do this:

d = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}


def parser(date):
    date = date.split()    # date = ['Mar', '31st,', '2014']
    for i, elem in enumerate(date):
        if i == 0:
            month = d[elem]    # month = '03'
        elif i == 1:
            date = elem[:len(elem) - 3]    # date = '31'
        else:
            year = elem    # year = '2014'
    return date + "/" + month + "/" + year    # '31/03/2014'

print parser('Mar 31st, 2014')

This will return 31/03/2014

Upvotes: 1

alecxe
alecxe

Reputation: 473893

You can use dateutil module:

>>> from dateutil.parser import parse
>>> s = 'Mar 31st, 2014'
>>> parse(s)
datetime.datetime(2014, 3, 31, 0, 0)

Upvotes: 4

Related Questions