Contents
Python datetime – Get Month as Number
To get Month Name Full Version using Python datetime, call strftime()
with %m
passed as argument.
Example 1: Get Month Number of Current Date
In the following example, we will take the current date, and get the month number.
#import datetime package
import datetime
#get current time
d = datetime.datetime.now()
#print date
print(d)
#get month number
print(d.strftime("%m"))
Run Output
2019-06-26 09:04:34.577489
06
Example 2: Get Month Number of Specific Date
In the following example, we will take a date 2019-08-12 and get the month number.
#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 Output
2019-08-12 00:00:00
08
Summary
In this tutorial, we extracted the month number from date using datetime package.
Related Tutorials
- Python String to Datetime
- Python Datetime to String
- How to get Weekday Short Version using Python datetime?
- Python Compare DateTime
- How to get Weekday Full Version using Python datetime?
- How to get Month Name Full Version using Python datetime?
- How to get Day of Month using Python datetime?
- How to get Weekday as Number using Python datetime?
- How to get Month Name Short Version using Python datetime?