Home >Backend Development >Python Tutorial >How Can I Get the Month Name from its Number in Python?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-20 18:18:30926browse

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:

<code class="python">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</code>

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:

<code class="python">print(mydate.strftime("%b"))  # Output: Dec</code>

The above is the detailed content of How Can I Get the Month Name from its Number in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn