Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract date ("05/Jan/2014") from string

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.) ?

like image 573
Basj Avatar asked Dec 25 '22 15:12

Basj


2 Answers

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'
like image 112
Martijn Pieters Avatar answered Jan 04 '23 22:01

Martijn Pieters


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.

like image 25
senshin Avatar answered Jan 04 '23 22:01

senshin