如何在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月7日

16K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.