如何在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