我有一個具有不同值的字符串列表,我試圖在列表中查找作為日期的字符串並返回日期的索引。我嘗試使用這樣的 dateutil 解析器:
x = ["test", "Hello", "abc", "27.02.2020"]
for item in x:
if parse(item) == True:
print(x.index(item))
這不起作用,因為我列表中的大多數字符串都不是日期,並且解析器無法識別不是日期的字符串格式。任何人都可以解決我如何以不同的方式解決這個問題?
有很多方法可以做到,最簡單的方法是使用pandas.to_datetime()
它引發異常(ParserError)如果不是日期
import pandas as pd #pip install pandas
def is_date(date_string):
try:
pd.to_datetime(date_string, format='%d.%m.%Y')
return True
except Exception:
return False
x = ["test", "Hello", "abc", "27.02.2020"]
for index, item in enumerate(x):
if is_date(item):
print(index)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句