首页 > 解决方案 > 将字符串日期拆分为多个日期列表

问题描述

我有以下列表,我正在尝试将元素相应地拆分为多个“日期”,我想编写一个函数来做到这一点,我不确定它是正则表达式还是datetime

x=["2- 7 MAY, 2020, 10-12 JUN, 2014","7 February, 2020, 6 February, 2020, 26 October, 2018","16 JUN, 2020, 24 JUL, 2020, 28 FEB, 2020, 15 SEPT, 2020, 8-11 MAY, 2023, 22 OCT, 2020","14 JUN, 2020"]

for i in x:
    temp=my_func(i)
    if len(temp)==1:
        date1=temp[0]
        date2=""
    elif len(temp)>=2:
        date1=temp[0]
        date2=temp[1]
    else:
        continue
    #rest of my code

这是预期的输出my_func

#my_func(x[0])=["2- 7 MAY, 2020", "10-12 JUN, 2014"]
#my_func([x[1]])=["7 February, 2020", "6 February, 2020", "26 October, 2018"]
#my_func(x[-1])=["14 JUN, 2020"]

标签: python

解决方案


根据你的例子,

import re
for i in x:
    temp =re.findall('\d.*?\d{4}',i)
#output
['2- 7 MAY, 2020', '10-12 JUN, 2014']
['7 February, 2020', '6 February, 2020', '26 October, 2018']
['16 JUN, 2020', '24 JUL, 2020', '28 FEB, 2020', '15 SEPT, 2020', '8-11 MAY, 2023', '22 OCT, 2020']
['14 JUN, 2020']

推荐阅读