python从文本中提取时间
时间: 2024-09-30 17:04:25 浏览: 27
在Python中,我们可以使用正则表达式库`re`或者第三方库如`dateutil.parser`来从文本中提取时间信息。以下是两种常见方法:
1. **使用正则表达式**:
```python
import re
def extract_time(text):
pattern = r"\b\d{1,2}:\d{2}(:\d{2})?(\s?[apm]\.?m?)?" # 格式匹配小时:分钟(:秒)? AM/PM
match = re.search(pattern, text)
if match:
return match.group()
else:
return None
text = "会议将在明天下午2点30开始"
time_extracted = extract_time(text)
```
2. **使用dateutil.parser**:
```python
from dateutil.parser import parse
def extract_time(text):
try:
time_obj = parse(text)
return time_obj.time() # 返回时间部分
except ValueError:
return None
text = "会议将在2023-03-05 14:30"
time_extracted = extract_time(text)
```
`dateutil.parser`能处理更复杂的时间格式,并自动解析。
阅读全文
相关推荐
















