简体   繁体   English

python正则表达式匹配并替换日期

[英]python regex match and replace dates

I need to match dates in form: 我需要以以下形式匹配日期:

January 10, 2012 2012年1月10日

And replace in form: 并以以下形式替换:

10 January 2012 2012年1月10日

Here is what I have so far: 这是我到目前为止的内容:

        pattern = re.findall(r'(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d\d,\s\d{4}', text)
        print pattern

How do i replace? 我该如何更换?

Use strptime() to parse the date and strftime() to generate the new string. 使用strptime()解析日期,并使用strftime()生成新字符串。 There is no reason to use a regex in this case. 在这种情况下,没有理由使用正则表达式。

In [1]: import time
In [2]: tm = time.strptime('January 10, 2012', '%B %d, %Y')
In [3]: time.strftime('%d %B %Y', tm)
Out[4]: '10 January 2012'

Just in general, something like this: 一般而言,如下所示:

find: ^(January) (\\d{1,2}), (\\d{4})$ replace $2 $1 $3 查找: ^(January) (\\d{1,2}), (\\d{4})$替换$2 $1 $3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM