用timezon替换日期的Python正则表达式

2024-05-29 02:13:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含各种时区日期的CSV文件,但是在将这些数据输入到测试之前,我想用unify值替换所有日期。你知道吗

日期列包含如下值, 2019-01-01 00:00:00+05:30 2018-12-31 18:30:00+00 2018-02-02 00:00:00-04:00

我想把它们换成

2019-01-01 00:00:00+00 2018-12-31 00:00:00+00 2018-02-02 00:00:00+00

如何编写正则表达式来覆盖所有可能的时区?你知道吗

我写道:

([0-9]){4}(-:?)([0-9]){2}(-:?)([0-9]){2} ([0-9]){2}:([0-9]){2}:([0-9]){2}(+-?)([0-9]){2}:([0-9]){2}

但是当它遇到2018-12-31 18:30:00+00时失败了,我怎么处理这个案子?你知道吗


Tags: 文件csv数据unify案子
3条回答

你不需要使用正则表达式,因为它似乎是直截了当的。您可以使用下面的代码段

ts = ["2019-01-01 00:00:00+05:30", "2018-12-31 18:30:00+00", "2018-02-02 00:00:00-04:00"]
l = [x.split()[0] + " 00:00:00+00" for x in ts]

或者

l = [x[:11] + "00:00:00+00" for x in ts]

解决此问题的最佳方法是使用**python datetime**(strp和strf)

如果您想使用regex来解决它,那么按照python文档https://docs.python.org/2/library/re.html 你可以这样做

def dashrepl(matchobj):
  return "{0} 00:00:00+00".format(matchobj.group(1))

import re
k="(\d{4}(-\d{2}){2})\s(\d{2}:?){3}.[\d:]+"
ab = re.sub(k, dashrepl, "2019-01-01 00:00:00+05:30")

timbiegeleisen是非常正确的,您不应该为此使用regex,您应该使用Python提供的datetime API。我的答案来源于jfshere在这篇文章中的一篇优秀文章

下面是Python 3.3+(因为你已经用Python 3.0标记了你的问题)

time_string = "2019-01-01 00:00:00+05:30"
# Parses a datetime instance from a string 
dt = datetime.datetime.strptime(time_string,'%Y-%m-%d %H:%M:%S%z')
# Changes the timezone to UTC by setting tzinfo
timestamp = dt.replace(tzinfo=datetime.timezone.utc).timestamp()
# Converts back to a datetime object
dt = datetime.datetime.fromtimestamp(timestamp)
# Formats and prints it out.
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z'))

对于Python versions < 3.3,对于aware datetime

    time_string = "2019-01-01 00:00:00+05:30"
    # Parses a datetime instance from a string 
    dt = datetime.datetime.strptime(time_string,'%Y-%m-%d %H:%M:%S%z')
    # Changes the timezone to UTC by setting tzinfo
    timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1)
    # Converts back to a datetime object
    dt = datetime.datetime.fromtimestamp(timestamp)
    # Formats and prints it out.
    print(dt.strftime('%Y-%m-%d %H:%M:%S %Z'))

术语

An aware object is used to represent a specific moment in time that is not open to interpretation

在我们的例子中,时区信息是已知的。你知道吗

相关问题 更多 >

    热门问题