Date retrieved ("05 / Jan / 2014") from the string

I would like to extract a date from a string, for example:

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 (it already β€œknows” the months: January, February, etc.)?

+4
source share
3 answers

If your language is English, then the standard datetimemodule will analyze the abbreviations of the month for you:

import datetime

date = datetime.datetime.strptime(inputvalue, '%d/%b/%Y').date()

C ( ) , , Python . locale.setlocale() locale.resetlocale(), .

:

date.strftime('%d/%m/%Y')

:

>>> 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'
+3

:

>>> import datetime
>>> datetime.datetime.strptime('15/Nov/2013', '%d/%b/%Y').strftime('%d/%m/%Y')
'15/11/2013'

, (, en_US), . , , , , .

+2

dateutil.parser, datetime python. , . datetime, .

>>> import dateutil.parser
>>> dateutil.parser.parse('15/Nov/2013').strftime("%d/%m/%Y")
'15/11/2013'

The function, at the same time, will be able to handle other formats, for example. YYYY-mm-DDwithout any changes on your part.

>>> dateutil.parser.parse('2013-11-15').strftime("%d/%m/%Y")
'15/11/2013'
+1
source

All Articles