Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在re.sub中使用变量,以便Python解析多个日期时间格式字符串?_Python_Regex_Dynamic_Datetime Format_Date Parsing - Fatal编程技术网

在re.sub中使用变量,以便Python解析多个日期时间格式字符串?

在re.sub中使用变量,以便Python解析多个日期时间格式字符串?,python,regex,dynamic,datetime-format,date-parsing,Python,Regex,Dynamic,Datetime Format,Date Parsing,我正在尝试使用一个函数将各种人工日期/时间格式字符串转换为与Python兼容的字符串(从'*yyyy-MMM-dd*'到'*%Y-%b-%d*') 到目前为止,我构建了下面的翻译字典(元组列表[('yyyy','%Y'),('MMM','%b'),…])),这样我就可以将输入格式字符串中的占位符字段转换为strptime'%x'字段,例如: 'yyyy-MMM-dd' --> '{5}-{3}-{12}' 但我下一步该怎么办?我尝试了多种方法: >>> re.sub('

我正在尝试使用一个函数将各种人工日期/时间格式字符串转换为与Python兼容的字符串(从
'*yyyy-MMM-dd*'
'*%Y-%b-%d*'

到目前为止,我构建了下面的翻译字典(元组列表
[('yyyy','%Y'),('MMM','%b'),…])
),这样我就可以将输入格式字符串中的占位符字段转换为
strptime'%x'
字段,例如:

'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
如何将匹配的内容传递到列表中?或者有其他方法可以做到这一点吗

编辑:我目前的方法是这样的,不完全满意:

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

既然可以使用dateutil.parser,为什么还要使用自己的呢

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

为什么不使用strtime:

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

为了澄清我的问题,我试图做的不是解析datetime对象。我已经有了datetime对象作为开始。我们的目标是接受C#type格式字符串(比如yyyy-MM-dd-HH:MM)而不是python样式(%Y-%b-%d)?你能使用标准术语还是提供引文?你是说“各种人类日期和时间格式”还是“strtime格式”?