0

I have a list in Python with different date formats:

list1 = ["30-4-1994", "1994-30-04", "30/04/1994",
         "30-apr-1994", "30/apr/1994","1994-30-apr"]

I want to format multiple date formats into a single date like dd-mm-yyyy

How can I do that?

4 Answers 4

4

In an ideal world, you know the format of your inputs.

Where this is not possible, I recommend you use a 3rd party library for mixed format dates.

Two libraries that come to mind are dateutil (via dateutil.parser.parse) and pandas (via pandas.to_datetime). Below is an example implementation with the former.

Note the only occasion when parser.parse was unsuccessful had to be covered with a manual conversion via datetime.strptime. datetime is part of the standard Python library.

from datetime import datetime
from dateutil import parser

list1 = ["30-4-1994", "1994-30-04", "30/04/1994",
         "30-apr-1994", "30/apr/1994","1994-30-apr"]

def converter(lst):
    for i in lst:
        try:
            yield parser.parse(i)
        except ValueError:
            try:
                yield parser.parse(i, dayfirst=True)
            except ValueError:
                try:
                    yield datetime.strptime(i, '%Y-%d-%b')
                except:
                    yield i

res = list(converter(list1))

# [datetime.datetime(1994, 4, 30, 0, 0),
#  datetime.datetime(1994, 4, 30, 0, 0),
#  datetime.datetime(1994, 4, 30, 0, 0),
#  datetime.datetime(1994, 4, 30, 0, 0),
#  datetime.datetime(1994, 4, 30, 0, 0),
#  datetime.datetime(1994, 4, 30, 0, 0)]

You can then format into strings any way you like using datetime.strptime:

res_str = [i.strftime('%d-%m-%Y') for i in res]

# ['30-04-1994',
#  '30-04-1994',
#  '30-04-1994',
#  '30-04-1994',
#  '30-04-1994',
#  '30-04-1994']
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this if you have only limited formats :

from datetime import datetime
list1=["30-4-1994","1994-30-04","30/04/1994","30-apr-
                     1994","30/apr/1994","1994-30-apr"]
for i in list1:
    for fmt in ('%Y-%m-%d', '%d-%m-%Y', '%d/%m/%Y',
                  '%Y-%d-%m', '%Y-%d-%b', '%d-%b-%Y', '%d/%b/%Y'):
        try:
           example_time =  datetime.strptime(i, fmt).date()
           final_output =  datetime.strftime(example_time, "%d-%m-%Y")
           print(final_output)
        except ValueError:
           continue

1 Comment

This also gives the time. To only get the date, you can do print(datetime.strptime(i, fmt).date()).
0

try the following code:

list1=["30-4-1994","1994-30-04","30/04/1994","30-apr-1994","30/apr/1994","1994-30-apr"]

mt=['jan','feb','mar','apr','may','jun','jul','aug','sep','sept','oct','nov','dec' ] 
dict={'jan':'01','feb':'02','mar':'03','apr':'04','may':'05','jun':'06','jul':'07','aug':'08','sep':'09','sept':'09','oct':'10','nov':'11','dec':'12'}    

for i in range(0,len(list1)):
    a=list1[i]
    b= a.split('-')
    d= a.split('/')

    if len(b)==3:
        c=b
    if len(d)==3:
        c=d
    #-----for year
    if int(c[0]) in range(1000,3000):
            yyyy = c[0]
            del(c[0])

    elif int(c[2]) in range(1000,3000):
            yyyy = c[2]
            del(c[2])
    #--------
    #-----for date
    if len(c[0])<2:
            c[0] =int(c[0])
            dd='%02d' %c[0]
    else :
            dd=c[0]
    #-----for month       
    if len(c[1])<2:
            c[1] =int(c[1])
            mm='%02d' %c[1]
    elif len(c[1])>2:
            if isinstance(c[1], str)== True  and c[1] in mt:
                   k= c[1]
                   mm=dict[k]
    else :
            mm=c[1]
    print(dd,'-',mm,'-',yyyy)

Comments

-1

Use datetime.strptime

You have to config those date format.

Example:

>>> from datetime import datetime
>>> example_time = datetime.strptime("2018-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
>>> example_time
datetime.datetime(2018, 1, 1, 0, 0)
>>> datetime.strftime(example_time, "%d-%m-%Y")
'01-01-2018'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.