datetime.datetime.strptime()
ValueError
如果字符串与格式不匹配,则会引发.
raw_input()
总是返回字符串对象,所以isinstance(data1, int)
总是False
如果你data1
在检查之前没有转换为int对象.
我建议使用try...except
捕捉到ValueError
类似下面的代码:
import datetime data1 = raw_input("data = ") print(data1) try: datetime.datetime.strptime(data1, '%Y-%m-%d') except ValueError: try: int(data1) except ValueError: print("str it is") else: print("int it is") else: print("date it is")
演示:
kevin@Arch ~> python2 input_check.py data = 2014-01-02 2014-01-02 date it is kevin@Arch ~> python2 input_check.py data = 12 12 int it is kevin@Arch ~> python2 input_check.py data = foobar foobar str it is