I would like to extract date from a string like :
15/Nov/2013
05/Jan/2014
and reformat it like this
15/11/2013
05/01/2014
Is there a ready-to-use function for this (that already "knows" months : Jan, Feb, etc.) ?
If your locale is english, then the standard datetime
module will parse month abbreviations for you:
import datetime
date = datetime.datetime.strptime(inputvalue, '%d/%b/%Y').date()
C (English month names) is the default locale, so this should work anywhere you don't set the Python locale explicitly. As long as you don't call locale.setlocale()
or locale.resetlocale()
anywhere you can count on the above to work correctly.
Formatting these back to a different format is then trivial:
date.strftime('%d/%m/%Y')
Demo:
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').date()
datetime.date(2013, 11, 15)
>>> datetime.datetime.strptime('05/Jan/2014', '%d/%b/%Y').date()
datetime.date(2014, 1, 5)
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').date().strftime('%d/%m/%Y')
'15/11/2013'
>>> datetime.datetime.strptime('05/Jan/2014', '%d/%b/%Y').date().strftime('%d/%m/%Y')
'05/01/2014'
Do this:
>>> import datetime
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').strftime('%d/%m/%Y')
'15/11/2013'
As Martijn Pieters noted, your locale should be English (e.g. en_US
) for this to work. If you haven't done anything to alter locale, it will presumably be some flavor of English.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With