使用日期查找器将字符串转换为日期
Convert string to date using datefinder
当我尝试使用日期查找器在 .txt 文件中查找日期时出现问题。我有一种感觉,我不必要地在数据类型之间切换以获得我想要的结果。
下方是生成生成器对象的 MWE,当更改为列表时该生成器对象又为空。我想获得格式为 %d-%m-%Y 的日期时间。
MWE:
import datefinder
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
for line in f:
if "creation date" in line:
date_line = str(line)
rev_date = datefinder.find_dates(_date_line)
dateutil 的解析器似乎做得更好:
import dateutil
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
dates = []
for line in f:
try:
dates.append(dateutil.parser.parse(line, fuzzy=True))
except dateutil.parser.ParserError:
pass
print(dates)
# [datetime.datetime(2021, 4, 25, 8, 52, 6)]
对于特定用例:
for line in f:
if "* Model creation date:" in line:
rev_date = dateutil.parser.parse(line, fuzzy=True)
break
print(rev_date)
# 2021-04-25 08:52:06
似乎 datefinder.find_dates
基于 :
工作。如果您可以在 creation date
之后删除 :
字符,则会得到正确的结果。
如果您的字符串始终包含 creation date:
您可以在 if
语句之后删除此子字符串:
import datefinder
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
for line in f:
if "creation date" in line:
date_line = line.replace('creattion date:', '')
rev_date = datefinder.find_dates(date_line)
当我尝试使用日期查找器在 .txt 文件中查找日期时出现问题。我有一种感觉,我不必要地在数据类型之间切换以获得我想要的结果。
下方是生成生成器对象的 MWE,当更改为列表时该生成器对象又为空。我想获得格式为 %d-%m-%Y 的日期时间。 MWE:
import datefinder
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
for line in f:
if "creation date" in line:
date_line = str(line)
rev_date = datefinder.find_dates(_date_line)
dateutil 的解析器似乎做得更好:
import dateutil
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
dates = []
for line in f:
try:
dates.append(dateutil.parser.parse(line, fuzzy=True))
except dateutil.parser.ParserError:
pass
print(dates)
# [datetime.datetime(2021, 4, 25, 8, 52, 6)]
对于特定用例:
for line in f:
if "* Model creation date:" in line:
rev_date = dateutil.parser.parse(line, fuzzy=True)
break
print(rev_date)
# 2021-04-25 08:52:06
似乎 datefinder.find_dates
基于 :
工作。如果您可以在 creation date
之后删除 :
字符,则会得到正确的结果。
如果您的字符串始终包含 creation date:
您可以在 if
语句之后删除此子字符串:
import datefinder
f = ['this is text', 'this is a date', '* Model creation date: Sun Apr 25 08:52:06 2021']
for line in f:
if "creation date" in line:
date_line = line.replace('creattion date:', '')
rev_date = datefinder.find_dates(date_line)