如何使用python3从只有日期格式的嵌套列表中识别列表?

时间:2019-04-10 06:24:14

标签: python-3.x

如何使用python3从只有日期格式的嵌套列表中识别列表?

 import re
 l=[["1","2","3"],["a","b","c"],["22/01/2019","23/01/2019"]]


for i,string in enumerate(l):
    data_cleaning_txn_date = re.findall(r"[\d]{1,2}/[\d]{1,2}/[\d]{4}",string)
    print(l)
  

预期输出:

22/01/2019
23/01/2019

2 个答案:

答案 0 :(得分:0)

您可以使用datetime.strptime库来解析日期时间对象。
    如果您可以成功解析它,则不能打印。

import re
import datetime
l=[["1","2","3"],["a","b","c"],["22/01/2019","23/01/2019"]]

#Function to parse string
def parse_datetime(date_str):

    date_obj = None
    try:
        date_obj = datetime.datetime.strptime(date_str, "%d/%m/%Y")
    except:
        pass

    return date_obj

for items in l:
    for item in items:
        #Only if parse_datetime is succussful, print the item
        if parse_datetime(item):
            print(item)
#22/01/2019
#23/01/2019

答案 1 :(得分:0)

import re
l=[["1","2","3"],["a","b","c"],["22/01/2019","23/01/2019"]]

for i,string in enumerate(l):
    for j in string:
        if re.findall(r"\d{1,2}/\d{1,2}/\d{4}", j):
            print(j)

the output:
22/01/2019
23/01/2019