【问题标题】:Convert date from mm/dd/yyyy to another format in Python在 Python 中将日期从 mm/dd/yyyy 转换为另一种格式
【发布时间】:2014-05-09 11:03:04
【问题描述】:

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

提前谢谢你!

【问题讨论】:

  • 您看过convert 实际包含的内容吗?
  • 它显示:['01', '01', '2009']
  • 你了解切片的工作原理吗?

标签: python datetime python-3.x


【解决方案1】:

不要重新发明轮子,而是使用 datetime 模块中的 strptime()strftime() 的组合,该模块是 python 标准库 (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

【讨论】:

    【解决方案2】:

    您可能想查看 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

    【讨论】:

      【解决方案3】:

      建议使用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'
      

      【讨论】:

        【解决方案4】:

        用斜线分割

        convert = replace.split('/')
        

        然后创建月份的字典:

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

        然后显示它:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-01-25
          • 2017-06-24
          • 1970-01-01
          • 2021-12-31
          • 2011-05-03
          • 1970-01-01
          • 2023-03-15
          • 1970-01-01
          相关资源
          最近更新 更多