How to get Month as Number using Python datetime?

Python datetime – Get Month as Number

To get Month Name Full Version using Python datetime, call strftime() with %m passed as argument.

Examples

1. Get month number from current date

In the following example, we will take the current date, and get the month number.

Python Program

# Import datetime package
import datetime

# Get current time
d = datetime.datetime.now()

# Print date
print(d)

# Get month number
print(d.strftime("%m"))
Run Code Copy

Output

2019-06-26 09:04:34.577489
06

2. Get month number from given date

In the following example, we will take a date 2019-08-12 and get the month number.

Python Program

# Import datetime package
import datetime

# Set specific date
d = datetime.datetime(2019, 8, 12)

# Print date
print(d)

# Get month number
print(d.strftime("%m"))
Run Code Copy

Output

2019-08-12 00:00:00
08

Summary

In this tutorial, we extracted the month number from date using datetime package.

Related Tutorials

Code copied to clipboard successfully 👍