用字符串替换ISO 8601的本地日期或日期时间

时间:2019-07-17 07:23:59

标签: python regex datetime substitution python-dateutil

我尝试用python 3.x中的字符串替换ISO 8601“ YYYY-MM-DDTHH:MI:SSZ”(UTC)的本地日期或日期时间(+02:00)

字符串示例:

x = "This is first example with dates 2019-07-01 21:30:20 and 2019-07-02 21:30:20"

我的代码可以正常运行,但效果不理想:

def date_to_iso(m):
    date_string = (dateutil.parser.parse(m.group(0))).astimezone(pytz.UTC).strftime("%Y-%m-%d" + "T" + "%H:%M:%S" + "Z")
    return iso_8601

y = re.sub(r"\d{4}(?:-\d{2}){2}" + r" \d{2}(?::\d{2}){2}", date_to_iso, x)

对于第一个示例,结果很好:

Out[269]: 'This is first example with dates 2019-07-01T19:30:20Z and 2019-07-02T19:30:20Z'

我的问题是如何修改日期,以使其具有不同的格式。例如:

x = "This is second example with dates 2019-07-01 and 2019-07-02 21:30:20, but there are dates 2019-07-10 07:00 and 2019-07-10 09 too"

,它应该返回如下内容:

Out[269]: 'This is second example with dates 2019-06-30T22:00:00Z and 2019-07-02T19:30:20Z, but there are dates 2019-07-10T05:00:00Z or 2019-07-10T07:00:00Z'

1 个答案:

答案 0 :(得分:0)

我发现了。这是代码,对我有好处:

import dateutil.parser
import pytz
import re

x = "This is second example with dates 2019-07-01 and 2019-07-02 21:30:20, but there are dates 2019-07-10 07:00 and 2019-07-10 09 too"

def datetime_to_iso(m):
    datetime_iso = (dateutil.parser.parse(m.group(0))).astimezone(pytz.UTC).strftime("%Y-%m-%d" + "T" + "%H:%M:%S" + "Z")
    return datetime_iso

x = re.sub(r"\d{4}(?:-\d{1,2}){2}" + r"( \d{1,2}(?::\d{1,2}(?::\d{1,2})?)?)?", datetime_to_iso, x)


print(x)
This is second example with dates 2019-06-30T22:00:00Z and 2019-07-02T19:30:20Z, but there are dates 2019-07-10T05:00:00Z and 2019-07-10T07:00:00Z too