我正在使用以下功能
def convStr2Date(given):
if type(given) != str:
return given
pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)'
rv = re.search(pattern, given).group(1)
if rv:
return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S')
這給了我錯誤 ValueError: time data '2021-10-01' does not match format '%Y-%m-%d %H:%M:%S
所以我添加了一個else:陳述句,但仍然出現相同的錯誤,我哪里出錯了?
試:
def convStr2Date(given):
if type(given) != str:
return given
pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|.*)'
rv = re.search(pattern, given).group(1)
if rv:
return datetime.strptime(rv, '%Y-%m-%d %H:%M:%S')
else:
return datetime.strptime(rv, '%Y-%m-%d')
uj5u.com熱心網友回復:
如果你想在沒有匹配的情況下回傳 None (或錯誤)(而不是只接受所有內容),你也可以這樣做
def convStr2Date(given):
if type(given) != str:
return given
pattern = '^(\d{4}-\d{2}-\d{2})( \d{2}:\d{2}:\d{2})?$'
rv = re.search(pattern, given)
if rv and rv.group(2): # Tests if second group matches
# (the part with the time of day)
# So there is given both date and time of day
return datetime.strptime(rv.group(0), '%Y-%m-%d %H:%M:%S')
elif rv: # Tests if the whole regex matches.
# Since the second part is optional
# the regex still matches if it is missing
# and because the first if tests if the
# second part exists and we are in the else branch
# we know only the first group matches
# which is only the date (without time)
return datetime.strptime(given, '%Y-%m-%d')
else: # If the whole regex does not match
# we know that it is not one of the two formats
# and therefore cannot be parsed
return None # Or raise some Error
#raise NotImplementedError
uj5u.com熱心網友回復:
如果你不關心確切的模式,你可以只測驗一個空間。無論如何,您的代碼將在其他日期模式下失敗。
from datetime import datetime
def convStr2Date(given: str) -> datetime:
if not isinstance(given, str):
raise ValueError(f"{given!r} is not a string")
date_format = '%Y-%m-%d'
if ' ' in given :
date_format = '%Y-%m-%d %H:%M:%S'
return datetime.strptime(given, date_format)
例子
for d in ['2021-10-02', '2018-10-20 01:21:23', 'not a date', 'notADate', 2, None]:
try:
print(convStr2Date(d))
except ValueError as e:
print(e)
輸出
2021-10-02 00:00:00
2018-10-20 01:21:23
time data 'not a date' does not match format '%Y-%m-%d %H:%M:%S'
time data 'notADate' does not match format '%Y-%m-%d'
2 is not a string
None is not a string
uj5u.com熱心網友回復:
洗掉它|.*以便它只匹配日期,然后如果它不匹配它將回傳None所以你需要確保在使用它之前不是這種情況.group(1)
def convStr2Date(given: str):
pattern = r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'
match = re.search(pattern, given)
if match is not None:
# only call group if the match exists
return datetime.strptime(match.group(1), '%Y-%m-%d %H:%M:%S')
else:raise NotImplementedError
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/347849.html
