簡體   English   中英

Python從字符串中提取不同格式的日期

[英]Python extract date with different formats from a string

我嘗試包 dateutil 從字符串中提取日期部分。 如果字符串中包含確切的日期,則效果很好,例如:

from dateutil.parser import parse
try: 
    date = parse(string, fuzzy=True)
    print(str(date)[:10])
except ValueError:
    print("no date in text")

string = "an example of date:8 march 2019"
output: 2019-03-08

string = "an example of date: 2019/3/8"
output: 2019-03-08

string = "an example of pure string"
output: no date in text

但是當字符串中包含數字而不是日期時,它會出錯並將其視為日期:

string = "an example of wrong date: 8"

output: 2022-03-08

我的問題是,如何使用這個包或類似的包來解決這個問題。 有一些與提取日期相關的帖子,例如Extract date from string in python ,但它們沒有涵蓋這個主題,它們適用於特定的日期格式。

非常感謝您的幫助!

似乎您想利用dateutil模塊的強大功能來解析自由格式的日期,但是它嘗試解析的默認日期種類和默認的規范化規則(當日期中缺少當前月份/年份時使用當前月份/年份)是不是你需要的。

您可以做的一件事是,如果該值可解析為整數值或要解析的字符串中沒有數字,則不要嘗試使用dateutil將該值解析為日期。

所以我的建議是滿足這兩個先決條件(你可以擴展列表,從而消除你的情況下對dateutil的默認誤解):

import re
from dateutil.parser import parse
try: 
    v = int(string)
    print("Seems like integer.")
except ValueError:  # requires that the date does not parse as proper int
    if re.search( r'\d', string) is not None:  # requires a digit in the string 
        try:
           date = parse(string, fuzzy=True)
           print(str(date)[:10])
        except ValueError:
           print("no date in text")
    else:
        print("Can't parse")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM