【问题标题】:Spell out each word of a date in Python 3在 Python 3 中拼出日期的每个单词
【发布时间】:2018-08-29 23:37:47
【问题描述】:

在 Python 3 中,我想将 2018-01-01 更改为“一月一日,两千一十八”。我查看了the Python datetime documentation 中的格式指南 但我没有看到拼写月份日期或拼写年份的格式。是否有一个众所周知的模块可以做到这一点(我是 Python 新手)?

【问题讨论】:

  • 您可能会发现 inflect 包很有用

标签: python-3.x date python-datetime


【解决方案1】:

使用 inflect 模块,正如@ Lakshay Garg 评论的那样,您可以这样做:

import datetime as dt, inflect

p = inflect.engine()

def date_in_words(x):
     a = dt.datetime.strptime(x,'%Y-%m-%d')
     return (a.strftime('%B ')+p.number_to_words(p.ordinal(int(a.day)))+', ' + 
     p.number_to_words(int(a.year)))

date_in_words('2018-03-14')
Out[259]: 'March fourteenth, two thousand and eighteen'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 2015-10-12
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2022-11-22
    相关资源
    最近更新 更多