如何在 Python 中从数字中检索月份名称
假设您有月份编号(例如 3)并想要获取其月份名称相应的名称(例如,March)。使用 Python,有一个简单的解决方案可以完成此任务。
使用 Datetime 模块
Python 的 datetime 模块提供了一种获取月份名称的方法。使用方法如下:
import datetime
# Get the current date
mydate = datetime.datetime.now()
# Retrieve the month name
month_name = mydate.strftime("%B")
# Print the month name
print(month_name) # Output: December
通过使用%B格式代码,可以获得完整的月份名称。例如:
如果您想要月份名称的缩写,请使用 %b 代替%B.
其他资源
有关此主题的更多详细信息,请参阅Python文档网站:
[Python Datetime strftime()方法](https://docs.python.org/3/library/datetime.html#strftime)
[编辑] 感谢@GiriB 的富有洞察力的评论,您还可以通过使用 %b 格式代码来使用更短的表示法,该代码返回缩写的月份name:
print(mydate.strftime("%b")) # Output: Dec
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3