如何以日期时间格式输入? [英] how do I take input in the date time format?

查看:154
本文介绍了如何以日期时间格式输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码,该代码从用户处获取了start_dateend_date,但是它引发了错误.
以下是代码:

I have written a code which take start_date and end_date from user but it is throwing an error.
Following is the code:

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后,错误弹出,如下所示:

and the error pops up after giving 1/1/2014 as input is as follows:

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

推荐答案

由于您使用的是print语句,因此好像您使用的是Python 2.x.

Since you are using print statement, seems like you are using Python 2.x .

在Python 2.x中,input()实际上会评估结果并返回,因此,如果输入的内容类似于1/1/2014或某个数字,则会得到一个整数(在这种情况下为1除以1除到2014年-> 0),而不是字符串.使用input()通常很危险,因为用户可以输入任何东西,而这会得到评估.

In Python 2.x , input() actually evaluates the result and returns, so, if you are entering something like 1/1/2014 or some number, you would get an integer (which in this case is 1 divided by 1 divided by 2014 -> 0 ), not a string. And it is generally dangerous to use input() , since user can input anything and that would get evaluated.

使用raw_input()代替,以获取字符串,例如-

Use raw_input() instead, to get the string, example -

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()相同.

In Python 3.x , raw_input() from Python 2 was renamed to input() , so using input() in python 3 is same as using raw_input() in Python 2.x .

这篇关于如何以日期时间格式输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆