user3307366
user3307366

Reputation: 327

Convert date from mm/dd/yyyy to another format in Python

I am trying to write a program that asks for the user to input the date in the format mm/dd/yyyy and convert it. So, if the user input 01/01/2009, the program should display January 01, 2009. This is my program so far. I managed to convert the month, but the other elements have a bracket around them so it displays January [01] [2009].

date=input('Enter a date(mm/dd/yyy)')
replace=date.replace('/',' ')
convert=replace.split()
day=convert[1:2]
year=convert[2:4]
for ch in convert:
    if ch[:2]=='01':
        print('January ',day,year )

Thank you in advance!

Upvotes: 12

Views: 68266

Answers (5)

date_string = input('Enter a date using the mm/dd/yyyy format: ')
date_list = date_string.split('/')
month = date_list[0]
day = date_list[1]
year_ = date_list[2]
print(month, day, ',', year_ )
input('Press enter to end: ')

Upvotes: 0

behzad.nouri
behzad.nouri

Reputation: 77951

As a suggestion use dateutil, which infers the format by itself:

>>> from dateutil.parser import parse
>>> parse('01/05/2009').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009-JAN-5').strftime('%B %d, %Y')
'January 05, 2009'
>>> parse('2009.01.05').strftime('%B %d, %Y')
'January 05, 2009'

Upvotes: 2

shrnkrn
shrnkrn

Reputation: 121

You might want to look into python's datetime library which will take care of interpreting dates for you. https://docs.python.org/2/library/datetime.html#module-datetime

from datetime import datetime
d = input('Enter a date(mm/dd/yyy)')

# now convert the string into datetime object given the pattern
d = datetime.strptime(d, "%m/%d/%Y")

# print the datetime in any format you wish.
print d.strftime("%B %d, %Y") 

You can check what %m, %d and other identifiers stand for here: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Upvotes: 6

Snoop Dogg
Snoop Dogg

Reputation: 60

Split it by the slashes

convert = replace.split('/')

and then create a dictionary of the months:

months = {1:"January",etc...}

and then to display it do:

print months[convert[0]] + day + year

Upvotes: 1

alecxe
alecxe

Reputation: 473813

Don't reinvent the wheel and use a combination of strptime() and strftime() from datetime module which is a part of python standard library (docs):

>>> from datetime import datetime
>>> date_input = input('Enter a date(mm/dd/yyyy): ')
Enter a date(mm/dd/yyyy): 11/01/2013
>>> date_object = datetime.strptime(date_input, '%m/%d/%Y')
>>> print(date_object.strftime('%B %d, %Y'))
November 01, 2013

Upvotes: 31

Related Questions