python正则匹配日期时间字符串举例
时间: 2023-08-27 21:13:44 浏览: 106
根据引用内容,你可以使用正则表达式来匹配日期时间字符串。举例来说,如果你有一个字符串"2021-10-31 12:30:45",你可以使用正则表达式来提取其中的日期时间值。根据引用,你可以使用(?P...)这个正则表达式来提取。你可以将日期和时间分别提取出来,如下所示:
```python
import re
str = "2021-10-31 12:30:45"
match = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2}) (?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})", str)
year = match.group('year')
month = match.group('month')
day = match.group('day')
hour = match.group('hour')
minute = match.group('minute')
second = match.group('second')
print(year, month, day, hour, minute, second)
```
这样,你就可以将日期时间字符串中的各个部分提取出来,分别赋值给对应的变量。在上面的例子中,输出将为:"2021 10 31 12 30 45"。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [python正则表达式,获取字符串中的片段/正则表达式提取字符串](https://blog.csdn.net/qq_45281807/article/details/127768011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python正则表达式如何匹配字符串](https://blog.csdn.net/weixin_36390615/article/details/113981523)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文