Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 891
user3307366 Avatar asked Mar 30 '14 01:03

user3307366


People also ask

How do you convert Ymd to DMY in Python?

We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime. Parameter: input is the string datetime.

How do I change the date format in a Dataframe in Python?

Function usedstrftime() can change the date format in python.


2 Answers

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
like image 162
alecxe Avatar answered Oct 05 '22 05:10

alecxe


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

like image 38
shrnkrn Avatar answered Oct 05 '22 06:10

shrnkrn