我试图想出一个函数来将各种人类日期/时间格式字符串转换为Python兼容的字符串(来自'*yyyy-MMM-dd*'
to '*%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