Explain Codes LogoExplain Codes Logo

Datetime current year and month in Python

python
datetime
date
strftime
Alex KataevbyAlex Kataev·Jan 27, 2025
TLDR

Fetch the current year and month using Python's datetime:

from datetime import datetime print(f"Year: {datetime.now().year}, Month: {datetime.now().month}")

This prints the year and month: "Year: YYYY, Month: MM".

Datetime object — a more detailed view

Creating a datetime object that only has the current year and month? Here's how it's done:

from datetime import datetime current_year = datetime.now().year current_month = datetime.now().month year_month_obj = datetime(current_year, current_month, 1) print(year_month_obj) # Fun Fact: Dates can't talk but they sure do tell!

What's the output? A datetime object bearing the current year & month, and the day set to 1.

Simplified approach with Python's date

In cases where you want the date but not the time, Python's date module saves the day:

from datetime import date today = date.today() print(f"Year: {today.year}, Month: {today.month}") # Calendar's latest offering!

Comparing dates is often a function of knowing the year and month. Using datetime attributes directly skirts unwanted string conversions and parsing with strftime and strptime.

Crafty formatting with strftime

Presenting a date aesthetically often necessitates formatting. strftime is the tool to sculpt a palatable string:

formatted_month = datetime.now().strftime('%B, %Y') # Transforms 'April, 2023' into something digestible! print(f"Current Month in all its glory: {formatted_month}")

Conversely, when you have a date string and wish to morph it into a datetime, strptime is your time wizard:

from datetime import datetime date_string = "2023-04" date_object = datetime.strptime(date_string, '%Y-%m') print(date_object) # It's like casting a spell to flip a string into a date!

Need for accurate padding

Accuracy in dealing with padded vs unpadded date components is paramount. January is 01, not 1. Keep your eyes peeled for padded (%m) and unpadded (%-m) directives, especially in precision-dependent systems.

The global standard — ISO 8601

For international applications, adhering to the ISO 8601 standard in representing dates and times is beneficial. Let's output the current date in ISO 8601 format using Python:

iso_date = datetime.now().isoformat() print(f"Current date in ISO 8601: {iso_date}") # Now you're fluent in ISO 8601!