如何将日,月,年转换为日期格式?

时间:2017-04-02 12:18:35

标签: python python-3.x

我一直在尝试运行一个将日,月,年转换为日期格式的python脚本。

我尝试过以下脚本;

# dateconvert2.py 
# Converts day month and year numbers into two date formats

def main():
    # get the day month and year
    day, month, year = eval(input("Please enter day, month, year numbers: "))

    date1 = str(month)+"/"+str(day)+"/"+str(year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "Novemeber", "December"]
    monthStr = months[month-1]
    date2 = monthStr+" " + str(day) + ", " + str(year)

    print("The date is", date1, "or", date2+ ".")
main()

结果应该是这样的;

>>> Please enter day, month,  and year numbers: 24, 5, 2003
The date is 5/24/2003 or May 24, 2003.

当我运行该程序时,出现了一条错误说明该行;

    monthStr = months[month-1]     

有索引错误。

我可以做些什么来改善这个?请帮忙

2 个答案:

答案 0 :(得分:2)

如果

monthStr = months[month-1]     

有索引错误,表示month小于1或大于12.您可以在此行之前检查它是否在正确的范围内。

一些注释

  • eval很危险,在这种情况下不需要。您可以使用splitmapint来提取整数。
  • 您可以使用format%02d一起显示日期,如果您想自己撰写
  • strftime and strptime完全按照自己的意愿行事。他们将字符串解析为日期时间并以任何给定格式显示datetime
  • 日历已有month_name。该列表有13个元素,第一个是空的。

修改后的代码:

def main():
    # get the day month and year
    day, month, year = map(int, input("Please enter day, month, year numbers: ").split(','))

    date1 = '%02d/%02d/%d' % (day, month, year)

    months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    if month > 0 and month < 13:
        month_str = months[month-1]
        ## alternative :
        # import calendar
        # month_str = calendar.month_name[month]
        date2 = '%s %d, %d' % (month_str, day, year)
        print("The date is", date1, "or", date2+ ".")
    else:
        print("Invalid month")
main()

举个例子:

Please enter day, month, year numbers: 24,12,2017
The date is 24/12/2017 or December 24, 2017.

但是:

Please enter day, month, year numbers: 24,0,2017
Invalid month

答案 1 :(得分:0)

day, month, year = eval(input("Please enter day, month, year numbers: "))

eval()在这里是不必要的,假设您的用户知道用逗号分隔,您可以使用:

day, month, year = input("Please enter comma seperated day, month, year numbers: ")

可能仅适用于2.x,请参阅下面的评论,抱歉出现混淆

然后关于输入,您应该验证您的数据:

if 1 <= month <= 12:
    if (month in [1,3,5,7,8,10,12]) and (day != 31):
        print 'error'
    elif (month in [4,6,9,11]) and (day != 30):   
        print 'error'
    elif (month==2) and (day not in [28,29]):
        print 'error'
else:
    print 'error'