"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Get the Month Name from its Number in Python?

How Can I Get the Month Name from its Number in Python?

Published on 2024-11-08
Browse:577

How Can I Get the Month Name from its Number in Python?

How to Retrieve Month Name from its Number in Python

Suppose you have the month number (e.g., 3) and want to obtain its corresponding name (e.g., March). Using Python, there's a straightforward solution for this task.

Using Datetime Module

Python's datetime module provides a method to obtain the month name. Here's how you can use it:

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

By using the %B format code, you can get the full month name. For example:

  • %B → December
  • %b → Dec

If you want the short notation of the month name, use %b instead of %B.

Additional Resources

For more details on this topic, refer to the Python documentation website:

[Python Datetime strftime() Method](https://docs.python.org/3/library/datetime.html#strftime)

[EDIT] Thanks to @GiriB's insightful comment, you can also use the shorter notation by using the %b format code, which returns the abbreviated month name:

print(mydate.strftime("%b"))  # Output: Dec
Release Statement This article is reprinted at: 1729419436 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3