I have dd-MMM-yyyy dates. How do i convert this to yyyyMMdd, in Python ?
For example i need to convert 20-Nov-2002 to 20021120
I have dd-MMM-yyyy dates. How do i convert this to yyyyMMdd, in Python ?
For example i need to convert 20-Nov-2002 to 20021120
 
    
    You can use datetime.datetime.strptime() to read the date in a specific format and then use .strftime() to write it back in your required format. Example -
>>> import datetime
>>> datetime.datetime.strptime('20-Nov-2002','%d-%b-%Y').strftime('%Y%m%d')
'20021120'
Formats -
%d - 2 digit date
%b - 3-letter month abbreviation
%Y - 4 digit year
%m - 2 digit month
More details about different supported formats can be found here.
 
    
     
    
    You can use re module to do that, like this:
import re                                                                   
text = '20-Nov-2002'.replace('Nov', '11')                                                        
print(re.sub(r'(\d+)-(\d+)-(\d+)', r'\3-\1-\2', text))  
output:
2002-20-11
But if you want convert the all month, not just Nov to 11. 
you can use the datetime module like this: 
import re, datetime           
month = datetime.datetime.strptime('Nov', '%b').strftime('%m')   
text = '20-{month}-2002'.format(month=month)
print(re.sub(r'(\d+)-(\d+)-(\d+)', r'\3-\1-\2', text))  
And the output is the same.
