如何在 Python 中從字串中提取日期?


在本文中,我們將瞭解如何在 Python 中從字串中提取日期。

第一種方法使用正則表示式。要使用它,請匯入 re 庫,如果尚未安裝,則安裝它。匯入 re 庫後,我們可以使用正則表示式“\d{4}-\d{2}-\d{2}”。

要從字串中提取日期,您必須首先了解日期的格式。要提取日期,只需使用正則表示式和“datetime.datetime.strptime”對其進行解析即可。例如,如果字串中的日期格式為YYYY−MM−DD,則可以使用以下程式碼提取和解析它。

示例

在下面給出的示例中,我們以字串作為輸入,並嘗試使用正則表示式找出字串中存在的日期。

import re, datetime
str1 = "My Date of Birth is 2006-11-12"

print("The given string is")
print(str1)

day = re.search('\d{4}-\d{2}-\d{2}', str1)
date = datetime.datetime.strptime(day.group(), '%Y-%m-%d').date()

print("The date present in the string is")
print(date)

輸出

上面示例的輸出如下所示:

The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12

使用 dateutil() 模組

第二種方法是使用dateutil()庫的 parser 類的 parse 方法。此方法返回字串中存在的任何日期。我們應該傳送一個引數 fuzzy 並將其設定為 True,格式應為YYYY−MM−DD。此方法計算字串中存在的日期並將其作為輸出返回。

示例

在下面給出的示例中,我們以字串作為輸入,並嘗試找出它是否包含任何日期。

from dateutil import parser
str1 = "My Date of Birth is 2006-11-12"

print("The given string is")
print(str1)

date = parser.parse(str1, fuzzy=True)
print("The date present in the string is")
print(str(date)[:10])

輸出

上面示例的輸出如下所示:

The given string is
My Date of Birth is 2006-11-12
The date present in the string is
2006-11-12

更新於: 2022-12-07

17K+ 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.