【问题标题】:How convert this string to iso 8601 with Python如何使用 Python 将此字符串转换为 iso 8601
【发布时间】:2017-04-25 14:40:24
【问题描述】:

我有这个字符串

14 Mai 2014

我想把它转换成iso 8601

我读过this answerthis one

首先我尝试将字符串转换为日期,然后将其转换为 iso 格式:

test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()

我收到了这个错误

ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'

【问题讨论】:

    标签: python datetime iso8601


    【解决方案1】:

    根据Python strftime reference %m 表示月份中的某一天,在您的情况下,“Mai”似乎是您当前语言环境中的月份名称,您必须使用这种%b 格式。所以你的代码应该是这样的:

    test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
    iso_date = test_date.isoformat()
    

    别忘了设置语言环境。

    适用于英语语言环境:

    >>> from datetime import datetime
    >>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
    >>> print(test_date.isoformat())
    2014-05-14T00:00:00
    

    【讨论】:

    • 另外,请参阅docs.python.org/3.6/library/… 以获取以日期格式输入的完整列表。
    • 仅供参考,我的答案是第一个。
    • @dikkini 是的,但另一个包含“setlocale(locale.LC_ALL, 'fr_FR')”,这正是我的问题的答案。
    【解决方案2】:

    您需要使用%b 令牌而不是%m
    要使用 %b 令牌,您必须设置语言环境。
    Python Documentation

    import datetime
    import locale
    
    locale.setlocale(locale.LC_ALL, 'fr_FR')
    test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
    iso_date = test_date.isoformat()
    

    结果将是'2014-05-14T00:00:00'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2011-07-19
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多