日期格式转换在windows上工作,但在Linux中会出现错误

2024-05-16 20:06:26 发布

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

我正在尝试将日期格式化为特定格式。该代码在使用python3.7的Windows上成功部署。但是,它在Linux Debian9.11-Oython3.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: time data '2019-04-11T00:00:00.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

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


Tags: 代码formatdatestringparselinuxwindows部署
2条回答

在Python3.5中,UTC偏移量中不能有冒号。你知道吗

UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).

在python3.7中,允许冒号。你知道吗

我最终用regex解决了这个问题,而且效果很好。你知道吗

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]

相关问题 更多 >