(format borrowed from piRSquared's answer)
if pd.to_datetime(df['date'], format='%d-%b-%Y', errors='coerce').notnull().all():
# do something
This is the LYBL—"Look Before You Leap" approach. This will return True
assuming all your date strings are valid - meaning they are all converted into actual pd.Timestamp
objects. Invalid date strings are coerced to NaT
, which is the datetime equivalent of NaN
.
Alternatively,
try:
pd.to_datetime(df['date'], format='%d-%b-%Y', errors='raise')
# do something
except ValueError:
pass
This is the EAFP—"Easier to Ask Forgiveness than Permission" approach, a ValueError
is raised when invalid date strings are encountered.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…