我有几个字符串,并且已经确定了它们上日期的某些格式,并且想识别每个字符串上的日期

an_2011_02_12_azar.mp3 ->this is yyyy_mm_dd
20121112_Marcel.mp3    ->this is yyyymmdd
cdani_270607.mp3       ->this is ddmmyy
lica_07_03_15.mp3      ->this is dd_mm_yy

为此,我有:

foo = """
an_2011_02_12_azar.mp3
20121112_Marcel.mp3   
cdani_270607.mp3     
lica_07_03_15.mp3  
"""
try:
    lines = foo.split('\n')
except AttributeError:
    lines = x
for line in lines:
     print(line)
     #deals with 2011_02_12 format
     match = re.search(r'\d{4}_\d{2}_\d{2}', line)
     date = datetime.datetime.strptime(match.group(), '%Y_%m_%d').date()
     print(date)

如何应用几个正则表达式以便可以识别日期?

===============>>#1 票数:1 已采纳

如果删除下划线:

datestr = line.replace('_', '')

那么只有两种日期格式可以处理: yyyymmddddmmyy 此外,每个日期字符串都将包含6到8位数字,您可以使用正则表达式模式r'\\d{8}|\\d{6}'

datestr = re.search(r'\d{8}|\d{6}', datestr).group()

然后可以用以下任一方法解析datestr

date = DT.datetime.strptime(datestr, '%d%m%y')

要么

date = DT.datetime.strptime(datestr, '%Y%m%d')

模式r'\\d{8}|\\d{6}'还将捕获一些可能不类似于日期的字符串,例如表示无效日期的数字。 我们可以使用try..except来捕获ValueErrors来处理这些情况。


import re
import datetime as DT

foo = """\
an_2011_02_12_azar.mp3
20121112_Marcel.mp3   
cdani_270607.mp3     
lica_07_03_15.mp3  
an_2011_13_12_azar.mp3
"""

for line in foo.splitlines():
    datestr = line.replace('_', '')
    datestr = re.search(r'\d{8}|\d{6}', datestr).group()
    try:
        # %y matches 2-digit years
        date = DT.datetime.strptime(datestr, '%d%m%y')
    except ValueError:
        try:
            # %Y matches 4-digit years
            date = DT.datetime.strptime(datestr, '%Y%m%d')
        except ValueError:
            # handle the error case
            date = None
    print('{:23} --> {}'.format(line, date))

产量

an_2011_02_12_azar.mp3  --> 2011-02-12 00:00:00
20121112_Marcel.mp3     --> 2012-11-12 00:00:00
cdani_270607.mp3        --> 2007-06-27 00:00:00
lica_07_03_15.mp3       --> 2015-03-07 00:00:00
an_2011_13_12_azar.mp3  --> None

  ask by cMinor translate from so

未解决问题?本站智能推荐: