将日期从mm/dd/yyyy转换为Python中的另一种格式

use*_*366 9 python datetime python-3.x

我正在尝试编写一个程序,要求用户以mm/dd/yyyy格式输入日期并进行转换.因此,如果用户输入01/01/2009,程序应显示2009年1月1日.这是我的程序到目前为止.我设法转换月份,但其他元素有一个括号围绕它们,所以它显示1月[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 )
Run Code Online (Sandbox Code Playgroud)

先感谢您!

ale*_*cxe 25

不要重新发明轮子和使用的组合strptime()strftime()datetime模块,该模块是Python标准库(的一部分的文档):

>>> 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
Run Code Online (Sandbox Code Playgroud)


小智 6

您可能希望查看python的datetime库,它将负责为您解释日期.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") 
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看%m,%d和其他标识符的含义:https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior