Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to extract only the month and day from a datetime object in Python?
To extract only the month and day from a datetime object in Python, you can use several approaches including the strftime() method, direct attribute access, or DateFormatter() for matplotlib plots.
Using strftime() Method
The strftime() method formats datetime objects into readable strings ?
from datetime import datetime
# Create a datetime object
dt = datetime(2023, 7, 15, 14, 30, 0)
# Extract month and day using strftime()
month_day = dt.strftime("%m-%d")
print("Month-Day:", month_day)
# With month name
month_day_name = dt.strftime("%B %d")
print("Month Day:", month_day_name)
Month-Day: 07-15 Month Day: July 15
Using Direct Attribute Access
You can directly access the month and day attributes from a datetime object ?
from datetime import datetime
dt = datetime(2023, 7, 15, 14, 30, 0)
# Extract month and day directly
month = dt.month
day = dt.day
print(f"Month: {month}")
print(f"Day: {day}")
print(f"Month-Day: {month:02d}-{day:02d}")
Month: 7 Day: 15 Month-Day: 07-15
Using DateFormatter for Matplotlib Plots
When working with time series data in matplotlib, use DateFormatter to display only month and day on the x-axis ?
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt, dates
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create sample data
df = pd.DataFrame({
'time': pd.date_range("2021-01-01 12:00:00", periods=10),
'speed': np.linspace(1, 10, 10)
})
fig, ax = plt.subplots()
ax.plot(df.time, df.speed)
ax.xaxis.set_major_formatter(dates.DateFormatter('M:%m\nD:%d'))
plt.show()
Format Options
| Format Code | Description | Example |
|---|---|---|
%m |
Month as zero-padded number | 07 |
%d |
Day as zero-padded number | 15 |
%B |
Full month name | July |
%b |
Abbreviated month name | Jul |
Conclusion
Use strftime() for formatted string output, direct attributes for numeric values, or DateFormatter for matplotlib plots. Each method serves different use cases depending on whether you need strings or integers.
Advertisements
