【问题标题】:how do I take input in the date time format?如何以日期时间格式输入?
【发布时间】:2015-10-01 23:12:27
【问题描述】:

我编写了一个代码,它从用户那里获取start_dateend_date,但它抛出了一个错误。
以下是代码:

from datetime import datetime
start_date = datetime.strptime(input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
end_date = datetime.strptime(input('Enter End date in the format m/d/y'), '%m/%d/%Y')
dates=['4/6/2013', '5/4/2013', '6/26/2013', '7/26/2013', '9/5/2013', '10/7/2013', '10/12/2013', '4/12/2014', '5/10/2014', '6/12/2014', '7/19/2014', '8/15/2014', '9/17/2014', '4/21/2015', '5/28/2015', '6/26/2015']

# this line creates a list of datetime objects from the given strings in list dates  

dt_dates = [datetime.strptime(date, '%m/%d/%Y') for date in dates]

in_between_dates = []
for d in dt_dates:
    if d >= start_date and d <= end_date:
        in_between_dates.append(d)

print [d.strftime('%m/%d/%Y') for d in in_between_dates]

输入1/1/2014后弹出错误如下:

Enter Start date in the format m/d/y1/1/2014
Traceback (most recent call last):
  File "C:\Users\Ayush\Desktop\UWW Data Examples\new csvs\temp.py", line 9, in <module>
    start_date = datetime.strptime(input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
TypeError: must be string, not int

【问题讨论】:

标签: python list datetime input types


【解决方案1】:

由于您使用的是 print 语句,因此您似乎使用的是 Python 2.x 。

在 Python 2.x 中,input() 实际上计算结果并返回,因此,如果您输入类似 1/1/2014 或某个数字之类的内容,您将得到一个整数(在本例中为 1 除以 1到 2014 -> 0 ),而不是字符串。而且使用 input() 通常很危险,因为用户可以输入任何内容,并且会被评估。

改用raw_input() 来获取字符串,例如-

start_date = datetime.strptime(raw_input('Enter Start date in the format m/d/y'), '%m/%d/%Y')
end_date = datetime.strptime(raw_input('Enter End date in the format m/d/y'), '%m/%d/%Y')

在 Python 3.x 中,Python 2 中的 raw_input() 被重命名为 input() ,因此在 Python 3 中使用 input() 与在 Python 2.x 中使用 raw_input() 相同。

【讨论】:

    【解决方案2】:

    对于 Python 2,使用 raw_input 而不是 input。对于 Python 3,input 很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多