arunan annamalai arunan annamalai - 25 days ago 8
Python Question

How to change the date format from "03-Nov-2016" to 11/3/2016

Below is the python code I tried in 2.7 ,

def date_format_change():
DB_date = "03-NOV-2016"
split2 = DB_date.split('-')
print split2[0]
M_date = float(round(split2[0]),2)
print M_date
Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9',
'OCT': '10', 'NOV': '11', 'DEC': '12'}
DB_Month = str(split2[1])
print DB_Month
M_Month = int(Month[DB_Month])
M_year = split2(2)
print M_year
Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year)
print Changed_format


date_format_change()

but i am getting error saying :

Traceback (most recent call last):
File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 17, in
03
date_format_change()
File "C:/Users/aannam002c/workspace/Website/Century/views.py", line 5, in date_format_change
M_date = float(round(split2[0]),2)
TypeError: a float is required

Process finished with exit code 1

Could any one can help with this

Answer

float() takes one argument and you have given two and also float type for dates doesn't look good. int would do the job.

This is probably what you want:

def date_format_change():
    DB_date = "03-NOV-2016"
    split2 = DB_date.split('-')
    M_date = int(split2[0])
    Month = {'JAN': '1', 'FEB': '2', 'MAR': '3', 'APR': '4', 'MAY': '5','JUN': '6', 'JUL': '7', 'AUG': '8', 'SEP': '9',
    'OCT': '10', 'NOV': '11', 'DEC': '12'}
    print (M_date)
    DB_Month = split2[1]
    print (DB_Month)
    M_Month = int(Month[DB_Month])
    M_year = split2[2]
    print (M_year)
    Changed_format = str(M_Month) +"/"+ str(M_date)+"/"+ str(M_year)
    print (Changed_format)

date_format_change()

It returns:

3
NOV
2016
11/3/2016