Python在re.sub中使用变量

时间:2013-09-12 15:28:27

标签: python regex dynamic

我正在尝试将一个将麻瓜风格日期格式字符串转换为兼容python的函数(从' yyyy-MMM-dd '到'%Y-%b- %d ')。 到目前为止,我构建了一个翻译字典(元组列表[('yyyy','%Y'),('MMM','%b'),...])并且能够完成这个:

来自'yyyy-MMM-dd'的

- >到'{5} - {3} - {12}'

我在下一步遇到问题。我尝试过多种方式:

>>> re.sub('({\d+})',translateList['\1'][1],'{5}-{3}-{12}')
TypeError: list indices must be integers, not str

>>> re.sub('({\d+})',translateList[int('\1')][1],'{5}-{3}-{12}')
ValueError: invalid literal for int() with base 10: '\x01'

>>> re.sub('({\d+})',translateList[eval('\1')][1],'{5}-{3}-{12}')
SyntaxError: unexpected EOF while parsing

如何将匹配的内容传递到列表中?或者这样的任何其他方式?

非常感谢!


编辑#1 目前最终还没有完全满意:

def _getDatetimeFormatStringFromMuggleString(input):
    muggleList = [
        ('yyyy','%Y'), ('yy','%Y'),                             # year
        ('MMMM','%B'), ('MMM','%b'), ('MM','%m'), ('M','%m'),   # Month
        ('dddd','%A'), ('ddd','%a'), ('dd','%d'), ('d','%d'),   # day
        ('HH','%H'), ('H','%H'), ('hh','%I'), ('h','%I'),       # hour
        ('mm','%M'), ('m','%M'),                                # minute
        ('ss','%S'), ('s','%S'),                                # second
        ('tt','%p'), ('t','%p'),                                # AM/PM
    ]

    for i in muggleList:
        if i[0] in input and '%'+i[0] not in input:
            input = input.replace(i[0], i[1])

    return input

2 个答案:

答案 0 :(得分:1)

为什么在使用dateutil.parser时自己动手?

import dateutil
outdate = dateutil.parser.parse(instr, yearfirst=True) 

答案 1 :(得分:0)

为什么不使用strptime

>>> from datetime import datetime
>>> datetime.strptime('2012-12-12', '%Y-%j-%d')
datetime.datetime(2012, 1, 12, 0, 0)