5 Best Ways to Extract Month and Year from Python DateTime Objects

πŸ’‘ Problem Formulation: When working with dates in Python, a common requirement is to extract just the month and year from a datetime object. For instance, given the input datetime.datetime(2023, 4, 5), the desired output might be “April 2023”. This article will explore various methods to achieve this output efficiently.

Method 1: Using strftime() Method

The strftime() method allows for custom-formatted strings based on the datetime object. It’s versatile and supports a wide array of format codes that specify which parts of the date to include in the output string.

Here’s an example:

from datetime import datetime

current_date = datetime.now()
formatted_date = current_date.strftime('%B %Y')
print(formatted_date)

Output: “April 2023”

This code snippet obtains the current date and time using datetime.now(), then formats it into a string that contains only the month (in full text) and the year using the strftime('%B %Y') method, resulting in a user-friendly format.

Method 2: Using datetime Attributes

Every datetime object in Python has attributes like year and month which can be used to access these values directly. Converting these to a string and formatting them is straightforward.

Here’s an example:

from datetime import datetime
import calendar

current_date = datetime.now()
month_year = f"{calendar.month_name[current_date.month]} {current_date.year}"
print(month_year)

Output: “April 2023”

This code involves directly using the month and year attributes from the datetime object. It utilizes the calendar module to convert the numerical month to its full name. The use of an f-string simplifies the construction of the final formatted string.

Method 3: Using pandas to_datetime() and strftime()

Pandas is a powerful data manipulation library that offers convenience functions such as to_datetime() for converting strings to datetime objects, which can then be formatted as desired using strftime().

Here’s an example:

import pandas as pd

date_string = "2023-04-05"
date_obj = pd.to_datetime(date_string)
formatted_date = date_obj.strftime('%B %Y')
print(formatted_date)

Output: “April 2023”

The given code converts a date string into a pandas Timestamp object using pd.to_datetime(). It then applies strftime() to format this timestamp into a string containing just the month and year, which is useful for creating human-readable date formats in data analysis tasks.

Method 4: Converting to Arrow Object for Formatting

Arrow is a third-party library that provides functions for creating, manipulating, formatting, and converting dates. By converting a datetime object to an Arrow object, we can then easily format it.

Here’s an example:

import arrow

current_date = arrow.now()
formatted_date = current_date.format('MMMM YYYY')
print(formatted_date)

Output: “April 2023”

Using the Arrow library, the snippet gets the current date and time, and formats it to include only the full month name and the year using the format('MMMM YYYY') method. Arrow’s date format syntax is similar to Python’s strftime() but can provide some enhanced flexibility for locale-specific formatting.

Bonus One-Liner Method 5: Using date() and format()

In one line of code, we can combine the versatility of Python’s string formatting with the accessibility of the datetime attributes to output the month and year.

Here’s an example:

from datetime import datetime

print(f"{datetime.now().date():%B %Y}")

Output: “April 2023”

This one-liner is a concise way to achieve our goal. We call datetime.now() to get the current date and time, then access the date() method to obtain a date object, and use Python’s formatting syntax :%B %Y within an f-string to directly output the formatted date.

Summary/Discussion

  • Method 1: strftime() Method. Strengths: Comes built into Python’s standard library, very versatile. Weaknesses: Requires memorizing format codes.
  • Method 2: datetime Attributes. Strengths: Uses built-in Python functionality, easy to read and maintain. Weaknesses: Requires manual formatting of the string representation.
  • Method 3: pandas to_datetime(). Strengths: Integrates easily with data analysis workflows, very powerful in handling different date formats. Weaknesses: Requires installation of the external pandas library.
  • Method 4: Arrow Library. Strengths: Provides a rich API for date manipulation and formatting. Weaknesses: Requires installation of the third-party arrow library, which might not be necessary for simple tasks.
  • Method 5: One-Liner using date() and format(). Strengths: Quick and concise. Weaknesses: Less explicit, which could potentially reduce readability for some users.