【问题标题】:Elegant way to convert date string from short to long format将日期字符串从短格式转换为长格式的优雅方法
【发布时间】:2022-01-27 10:29:32
【问题描述】:

假设我有一个日期字符串

09 NOV 2012

我想把它转换成

9 November 2021

在 Python 中,哪种方式最快、更优雅?当然我可以创建一个像

这样的字典
{ "JAN": "January", ... "DEC": "December" }

创建一个循环,从一天中去除前导零,并在一个月内使用 replace(),但我正在寻找一种紧凑而优雅的方式来做到这一点。

【问题讨论】:

    标签: python replace


    【解决方案1】:

    使用来自datetime.datetimestrptime()strftime() (check the docs)

    >>> spam = '09 NOV 2012'
    >>> from datetime import datetime
    >>> datetime.strptime(spam, '%d %b %Y').strftime('%d %B %Y')
    '09 November 2012'
    

    编辑:正如 @NizamMohamed 在 cmets 中所提到的 - 在格式字符串中使用 %e 表示没有前导零的日期,但有额外的空间。您可以使用str.strip() 将其删除。

    >>> datetime.strptime(spam, '%d %b %Y').strftime('%e %B %Y')
    ' 9 November 2012'
    

    【讨论】:

    • %e 表示没有前导零的月份。
    【解决方案2】:

    您可以尝试以下方法吗:

    import re
    
    rep = { "JAN": "January", "NOV": "November" }
    text = '09 NOV 2012'
    # use these three lines to do the replacement
    rep = dict((re.escape(k), v) for k, v in rep.items()) 
    pattern = re.compile("|".join(rep.keys()))
    text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
    print(text)
    

    输出:

    '09 November 2012'
    

    【讨论】:

    • 这会忽略语言环境。不好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2020-11-20
    • 2016-06-12
    • 1970-01-01
    • 2013-12-28
    • 2014-01-18
    相关资源
    最近更新 更多