未指定日期时间输入值

太空鬼

我目前正在学习Python,并亲自学习了一些数据验证。我一直坚持的一部分是日期和时间验证。此程序需要多个参数,包括date_starttime_startdate_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"作为strptime调用的第二个参数。但这还要求您更改将full_date_start和full_date_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")
    ...

希望能解决您的问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章