【问题标题】:Date format conversion works on windows but gives an error in Linux日期格式转换在 Windows 上有效,但在 Linux 中出错
【发布时间】:2020-01-28 22:30:49
【问题描述】:

我正在尝试将日期格式化为特定格式。该代码使用 Python 3.7 在 Windows 上成功部署。但是,它不适用于 Linux Debian 9.11 - Oython 3.5。想不出解决办法。非常感谢任何帮助。

def parse_date(date_string: str, date_format: str) -> str:
    """
    '2019-04-12T00:00:00.000-07:00' --> "%Y-%m-%dT%H:%M:%S.%f%z"
    '2019-04-28T07:25:39.668Z' --> "%Y-%m-%dT%H:%M:%S.%fZ"
    """
    req_date = dt.datetime.strptime(date_string, date_format)
    return req_date.strftime("%Y-%m-%d")

适用于 Windows

parse_date('2019-04-11T00:00:00.000-07:00', "%Y-%m-%dT%H:%M:%S.%f%z")

在 Linux 上失败

parse_date('2019-04-11T00:00:00.000-07:00', "%Y-%m-%dT%H:%M:%S.%f%z")

ValueError: 时间数据 '2019-04-11T00:00:00.000-07:00' 不匹配 格式 '%Y-%m-%dT%H:%M:%S.%f%z'

预期返回值:'2019-04-11'

【问题讨论】:

  • 您在 Linux 中的 Python 版本是什么? python 2.7 版的 strptime 中没有 %z。
  • 我已经更新了有关版本和操作系统的信息。

标签: python python-3.5


【解决方案1】:

我最终使用正则表达式来解决这个问题并且它有效。

def parse_date_regex(date_string: str) -> str:
    """
    :return:
    """
    date = re.split('(\d{4}-\d{2}-\d{2})', date_string)
    return [res for res in date if len(res) == 10][0]

【讨论】:

    【解决方案2】:

    在 Python 3.5 中,您的 UTC 偏移量中不能有冒号。

    +HHMM 或 -HHMM 形式的 UTC 偏移量(如果对象是幼稚的,则为空字符串)。

    在 Python 3.7 中更改为允许使用冒号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2019-08-03
      • 2016-07-23
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多