在 python 中使用 datetime.datetime 从用户获取输入日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15581629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting input date from the user in python using datetime.datetime
提问by Rob Stark
I am trying to get input date from the user and store it in the form of
我正在尝试从用户那里获取输入日期并将其存储在
dt_start = dt.datetime(2006, 1, 1)
I am currently doing this:
我目前正在这样做:
i = str(raw_input('date'))
dt_start = dt.datetime(i)
But it throws an error:
但它抛出一个错误:
Traceback (most recent call last):
File "C:/.../sim.py", line 18, in <module>
dt_start = dt.datetime(i)
TypeError: an integer is required
Thanks for the help guys!
感谢您的帮助!
回答by A. Rodas
If you are using the %Y, %m, %dformat, you can try with datetime.strptime:
如果您正在使用该%Y, %m, %d格式,您可以尝试使用datetime.strptime:
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
回答by Johnny88520
datetime() only takes int as parameter.
datetime() 只接受 int 作为参数。
Try this:
尝试这个:
from datetime import datetime
date_entry = input('Enter a date (i.e. 2017,7,1)')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)

