簡體   English   中英

如果字符串具有不同日期格式的日期,如何從字符串中提取日期

[英]How to extract date from a string if the string has date that in are in different date format

我有一個包含多個字符串的列表,其中包含格式為“日期為 2018 年 1 月 23 日”或“日期 23.11.2018”的數據,並且日期主要位於字符串的末尾,有人可以告訴我如何使用提取日期python 或任何其他方法

    from datetime import datetime

    allYears = ['y','-y','Y']
    allMonths = ['b','B','m','-m']
    allDays = ['d','-d']


    def checkIfDate(dateRecieved):
        for year in allYears:
        for month in allMonths:
        for day in allDays:
            for separator in [['/', ' '], ['/', '.'], [' ', '/'], ['.', '/'], [' ', '.'], ['.', ' '], ['.', '.'], ['/', '/'], [' ', ' '],['rd', '/'], ['rd', '.'], ['rd', ' '], ['th', '/'], ['th', '.'], ['th', ' ']]:
                try:
                    if separator[0] in ['th', 'rd']:
                        date_time_obj = datetime.strptime(dateRecieved, f'%{day}{separator[0]} %{month}{separator[1]}%{year}')
                    else:
                        date_time_obj = datetime.strptime(dateRecieved, f'%{day}{separator[0]}%{month}{separator[1]}%{year}')
                except:
                    pass
                else:
                    print(year, month, day, separator)
                    print(date_time_obj)

    date_time_str = '18rd Dec.2019'

    checkIfDate(date_time_str)

如果日期采用以下形式,則此代碼有效:

  • 2019 年 12 月 18 日
  • 18.Dec/2019
  • 2019 年 12 月 18 日
  • 2019 年 12 月 18 日

但是,如果/和 . 等分隔符周圍有空格,這將不起作用 如:-

  • 2019 年 12 月 18 日
  • 12 月 18 日 2019
  • 2019 年 12 月 18 日

抱歉,如果這不是您要找的

暫無
暫無

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

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