Wednesday, July 16, 2014

How to convert a unicode date to mm/dd/yyyy

Code
from datetime import datetime                                          #1
unicodeDate = 'Jul162014'                                              #2
print datetime.strptime(unicodeDate,'%b%d%Y').strftime('%m/%d/%Y')     #3


How this works - Line by Line

from datetime import datetime                                          #1
 
Imports the datetime class from the datetime module


unicodeDate = 'Jul162014'                                              #2

I'm creating an example variable for the date in unicode format and calling it unicodeDate

print datetime.strptime(unicodeDate,'%b%d%Y').strftime('%m/%d/%Y')     #3

I'm printing the results of calling two methods.  The first method, strptime is taking the unicodeDate and the format of the date, '%b%d%Y', and returns a datetime object.  This datetime object is then converted into a string by the strftime method and output in the requested format '%m/%d/%Y'.

1 comment: