我正在定义一个新函数
from dateutil.parser import parse as dateparse
def validate(timestamp):
if (timestampe is a true timestamp of proper year, month, day):
print("Yes it is correct format")
else:
print("No. It is not in proper format")
#Example:
day1 = dateparse('2018-01-01')
print(type(day1))
>> <class 'datetime.datetime'>
day2 = '2018-10-7'
print(type(day2))
>> <class 'str'>
# Now above function should predict above results
validate(day1)
>> Yes it is correct format
validate(day2)
>> No. It is not in proper format上面定义的验证函数的内容应该是什么才能实现上面的功能?
发布于 2019-03-21 08:35:40
您不需要dateparse,因为它尝试猜测格式,而不是强制执行特定的格式。
相反,您希望使用datetime.strptime,并使用更严格的模板。此外,您应该在strptime调用周围使用try/except分支,而不是使用strptime/except分支。
通过阅读代码here,您可以找出用作strptime模板的正确格式。
https://stackoverflow.com/questions/55272068
复制相似问题