2017-06-30 38 views
2

我目前正在學習Python,並將其自行學習以獲取一些數據驗證。我遇到的一個問題是日期和時間驗證。該程序需要許多參數,包括date_start,time_start,date_endtime_end。這個問題是我需要ISO格式的。一旦採用這種格式,我需要確保它們是有效的。這就是我卡住的地方。datetime在未指定時輸入值

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 

這種檢查應該失敗,或者我認爲它應該有,因爲每天是不提供。任何幫助將不勝感激,如果有更簡單的方法來做到這一點,我會接受。謝謝!

回答

4

如果檢查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") 
    ... 

我希望解決您的問題。

+0

解決了這個問題。感謝Felipe! – spaceghost

+0

它不會自動填充當天嗎? – Alter

+2

之前沒有這樣做,只是'16'分成兩半,'1'去了一天,'6'去了小時。通過添加一個空白區域,您正在強制尋找空間前一天和空間後一小時。 –