在re.sub中使用变量,以便Python解析多个datetime格式的字符串吗? [英] Use variable in re.sub, for Python parsing multiple datetime-format strings?

查看:188
本文介绍了在re.sub中使用变量,以便Python解析多个datetime格式的字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提供一个将各种人类日期/时间格式字符串转换为Python兼容字符串的功能(来自'* yyyy-MMM-dd *''*%Y-%b-%d *')。

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*').

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

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?

编辑:我当前的方法是这样,没有完全满意:

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


推荐答案

为什么要滚动您的

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

这篇关于在re.sub中使用变量,以便Python解析多个datetime格式的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆