问题
I'm trying to come up with a function to translate various human date/time-format strings to Python compatible ones (from '*yyyy-MMM-dd*'
to '*%Y-%b-%d*'
).
So far I built the translate dictionary below (a list of tuples [('yyyy','%Y'),('MMM','%b'),...]
) so I can convert placeholder fields in input format-strings into strptime '%x'
fields e.g.:
'yyyy-MMM-dd' --> '{5}-{3}-{12}'
But what do I do next? I've tried multiple ways:
>>> 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
How do I pass what matched into the list? Or any other way to so this?
EDIT: My current approach is this, not fully satisfied:
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
回答1:
Why roll your own when you can use dateutil.parser?
import dateutil
outdate = dateutil.parser.parse(instr, yearfirst=True)
回答2:
Why don't you use strptime
:
>>> from datetime import datetime
>>> datetime.strptime('2012-12-12', '%Y-%j-%d')
datetime.datetime(2012, 1, 12, 0, 0)
来源:https://stackoverflow.com/questions/18768412/use-variable-in-re-sub-for-python-parsing-multiple-datetime-format-strings