在Python中将日期从mm/dd/yyyy转换为其他格式

12 投票
5 回答
67555 浏览
提问于 2025-04-18 00:30

我正在尝试写一个程序,让用户输入日期,格式是 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 )

提前谢谢你们!

5 个回答

0
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: ')

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

1

先用斜杠把它分开

convert = replace.split('/')

然后创建一个包含月份的字典:

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

最后要显示它,可以这样做:

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

建议你使用 dateutil 这个库,它可以自动识别日期格式:

>>> 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'
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") 

你可以在这里查看 %m、%d 以及其他标识符的含义:https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

31

别重复造轮子,直接使用Python标准库中的datetime模块里的strptime()strftime()这两个函数就可以了。你可以在这个链接找到相关的文档: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

撰写回答