gpt4 book ai didi

python - 未指定日期时间输入值

转载 作者:行者123 更新时间:2023-11-28 22:26:24 25 4
gpt4 key购买 nike

我目前正在学习 Python,并主动学习了一些数据验证。我一直坚持的一个部分是日期和时间验证。该程序采用多个参数,包括 date_starttime_startdate_endtime_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")
...

希望这能解决您的问题。

关于python - 未指定日期时间输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44852206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com