Formatting Dates – Python

We have a date like this

3rd April 2013

and we want to change it to this


We can change the date format using the datetime module.

In this module we can use strptime( ) to tell Python that the string is a date, and then strftime( ) to change the date to the format we want.

Getting the String ready

Using the terminal…

# first we import the module
>>> from datetime import datetime

# and we have our date as a string
>>> str_my_date = '3rd April 2013'

One of the problems we have is that the day has a suffix, in this case ‘rd’. This will give us an error when using strptime( ) so we need to get rid of it with regex.

# so we import re
>>> from re import sub

# and we remove all possible suffixes
>>> str_good_date = sub('(st|nd|rd|th)','',str_my_date,1)

# let's check it...
>>> print str_good_date
3 April 2013

in the sub( ) function we add the 1 parameter at the end so that it only removes the first instance of possible suffixes. This means that, if you have a date such as ‘1st August’, it will not end up as ‘1 Augu’.

strptime( )

Good, now we can put the date into strptime( ) to tell python that this is a date.

There is a very long list of directives and date types, but I will only talk about the ones that matter for this example.

We have three things, a day decimal, a month name, and a full year decimal. These correspond to the following directives %d for the day decimal (3), %B for the full month name (April), and %Y for the full year decimal.

So the way the date is written in our string is %d %B %Y, with a space separating each.

Using these directives, we can tell python how the date is written in our string

>>> date_format = datetime.strptime(str_good_date,'%d %B %Y')

Good, now Python knows that we have a date and not a string. It also knows the correct day, month and year. Now we can use strftime( ) to change it to what ever we want.

strftime( )

Since we want to end up with 2013-04-03, we need everything in decimals, the year (which is %Y), the month (%m), and the day (%d). We also want them separated by a dash '-'.

Therefore, the new format will be like this


So using strftime( ), this is how it’s done

>>> str_formated_date = date_format.strftime('%Y-%m-%d')

# let's check it
>>> print str_formated_date


All Together

from re import sub
from datetime import datetime

str_my_date = '3rd April 2013'
str_good_date = sub('(st|nd|rd|th)','',str_my_date,1)
date_format = datetime.strptime('%d %B %Y')
str_formated_date = strfptime('%Y-%m-%d')

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s