我目前正在学习Python,并开始学习一些数据验证。我一直坚持的一点是日期和时间的确认。这个程序接受许多参数,包括date_start
、time_start
、date_end
和time_end
。关键是我需要ISO格式的。一旦采用这种格式,我需要确保它们是有效的。那就是我被困的地方。你知道吗
from datetime import datetime
def validate_date(date_start, time_start, date_end, time_end):
full_date_start = date_start + time_start
full_date_end = date_end + time_end
try:
formatted_time_start = datetime.strptime(full_date_start, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")
formatted_time_end = datetime.strptime(full_date_end, "%Y-%m-%d%H:%M:%S").isoformat(sep="T", timespec="seconds")
return True
except ValueError:
return False
date_start = "2017-06-29"
time_start = "16:24:00"
date_end = "2017-06-"
time_end = "16:50:30"
print(validate_date(date_start, time_start, date_end, time_end))
print("Date Start: " + date_start + "\nTime Start: " + time_start + "\nDate End: " + date_end + "\nTime End: " + time_end)
我测试了一些代码,去掉了date_end
的日期,得到的结果是
2017-06-01T06:50:30
这张支票应该没有通过,或者我认为应该是因为一天没有供应。任何帮助都将不胜感激,如果有更简单的方法,我会接受。谢谢您!你知道吗
如果在执行应该失败的行之前检查
full_date_end
的值,您会得到:"2017-06-16:50:30"
,并且由于您要查找的格式类似于"%Y-%m-%d%H:%M:%S"
,因此它会选择16的第一个数字作为日值,第二个数字作为小时值。你知道吗为了避免这种情况,我建议使用以下格式:
"%Y-%m-%d %H:%M:%S"
作为strtime调用的第二个参数。但这也要求您更改定义full\u date\u start和full\u date\u end的行:我希望这能解决你的问题。你知道吗
相关问题 更多 >
编程相关推荐