[英]How to extract date from a string if the string has date that in are in different date format
我有一個包含多個字符串的列表,其中包含格式為“日期為 2018 年 1 月 23 日”或“日期 23.11.2018”的數據,並且日期主要位於字符串的末尾,有人可以告訴我如何使用提取日期python 或任何其他方法
from datetime import datetime
allYears = ['y','-y','Y']
allMonths = ['b','B','m','-m']
allDays = ['d','-d']
def checkIfDate(dateRecieved):
for year in allYears:
for month in allMonths:
for day in allDays:
for separator in [['/', ' '], ['/', '.'], [' ', '/'], ['.', '/'], [' ', '.'], ['.', ' '], ['.', '.'], ['/', '/'], [' ', ' '],['rd', '/'], ['rd', '.'], ['rd', ' '], ['th', '/'], ['th', '.'], ['th', ' ']]:
try:
if separator[0] in ['th', 'rd']:
date_time_obj = datetime.strptime(dateRecieved, f'%{day}{separator[0]} %{month}{separator[1]}%{year}')
else:
date_time_obj = datetime.strptime(dateRecieved, f'%{day}{separator[0]}%{month}{separator[1]}%{year}')
except:
pass
else:
print(year, month, day, separator)
print(date_time_obj)
date_time_str = '18rd Dec.2019'
checkIfDate(date_time_str)
如果日期采用以下形式,則此代碼有效:
但是,如果/和 . 等分隔符周圍有空格,這將不起作用。 如:-
抱歉,如果這不是您要找的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.