How to convert day, month, year format to date?
I am trying to run a python script that converts the date, month, year format to date.
I tried to execute the following script;
# dateconvert2.py
# Converts day month and year numbers into two date formats
def main():
# get the day month and year
day, month, year = eval(input("Please enter day, month, year numbers: "))
date1 = str(month)+"/"+str(day)+"/"+str(year)
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
monthStr = months[month-1]
date2 = monthStr+" " + str(day) + ", " + str(year)
print("The date is", date1, "or", date2+ ".")
main()
The result should look like this:
>>> Please enter day, month, and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.
When I ran the program, an error appeared indicating that the line;
monthStr = months[month-1]
had an index error.
What can I do to improve this? Please, help
+3
source to share
2 answers
If a
monthStr = months[month-1]
had an index error, which means it month
was either less than 1 or greater than 12. You can check it in the correct range up to this line.
A few notes
-
eval
dangerous and unnecessary in this case. You can usesplit
,map
andint
to extract integers. - you can use
format
with%02d
to show dates if you want to write this yourself -
strftime
andstrptime
do exactly what you want. They parse the string into datetime and display itdatetime
in any format. - the calendar already has
month_name
. There are 13 items in the list and the first one is empty.
Modified code:
def main():
# get the day month and year
day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))
date1 = '%02d/%02d/%d' % (day, month, year)
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
if month > 0 and month < 13:
month_str = months[month-1]
## alternative :
# import calendar
# month_str = calendar.month_name[month]
date2 = '%s %d, %d' % (month_str, day, year)
print("The date is", date1, "or", date2+ ".")
else:
print("Invalid month")
main()
As an example:
Please enter day, month, year numbers: 24,12,2017
The date is 24/12/2017 or December 24, 2017.
but:
Please enter day, month, year numbers: 24,0,2017
Invalid month
+2
source to share
day, month, year = eval(input("Please enter day, month, year numbers: "))
eval () is not required here if your user knows to separate with commas, which you can simply use:
day, month, year = input("Please enter comma seperated day, month, year numbers: ")
can only work in 2.x, see comments below, sorry for confusion
then in regards to input, you should validate your data:
if 1 <= month <= 12:
if (month in [1,3,5,7,8,10,12]) and (day != 31):
print 'error'
elif (month in [4,6,9,11]) and (day != 30):
print 'error'
elif (month==2) and (day not in [28,29]):
print 'error'
else:
print 'error'
0
source to share