我收到一個POST
請求的日期值,它具有這種格式20220509T000000Z
。
在我正在處理的系統中,有時用戶可能會發送錯誤的日期值,例如2022059T000000Z
和2022509T000000Z
。該日期在我們的資料庫中保存為字串,但如果它不正確,我們稍后會在進行一些計算和顯示資訊時遇到問題。
所以,我正在尋找一種在 Python 中驗證字串是正確日期格式的方法,如下所示:
#parameter date is the string I receive on the POST
def validate(date):
if date is valid:
# a valid date would be 20220509T000000Z
return true
else:
# an incorrect date would be 2022509T000000Z
return 'Error, incorrect date values'
提前致謝
uj5u.com熱心網友回復:
一種方法是嘗試使用 dateutil 決議器,但除外:
import dateutil
#parameter date is the string I receive on the POST
def validate(date):
try:
dateutil.parser.parse(date)
# a valid date would be 20220509T000000Z
return True
except Exception as e:
# an incorrect date would be 2022509T000000Z
return 'Error, incorrect date values'
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470813.html
上一篇:在YYMMDD10中獲取SAS中的當前日期。日期資料型別的格式
下一篇:Java日期區域格式到簡單格式