[Python] Basics of the date Type: Handling Year, Month, and Day

When you want to handle “only dates without time” in Python, use the date class from the datetime module.

This class is suitable for scenarios where time information (hours, minutes, seconds) is unnecessary, such as birthdays, anniversaries, or deadlines. This article explains how to generate date objects and access their attributes.

目次

Key Attributes of the date Object

The date object has the following three attributes, each accessible as an integer (int).

AttributeTypeDescriptionExample
yearintRepresents the year (AD).2025
monthintRepresents the month (1-12).10
dayintRepresents the day (1-31).12

Implementation Example: Managing Product Release Dates

This code example defines a specific date (product release date) and displays its components. It also introduces the today() method to get the current execution date.

Source Code

from datetime import date

# 1. Create a date object specifying a specific date
# Arguments: (Year, Month, Day)
release_date = date(2025, 11, 20)

print(f"Release Date (date): {release_date}")
print("-" * 20)

# Accessing each attribute
# Parentheses () are not needed; access via variable_name.attribute_name
print(f"Year  : {release_date.year}")
print(f"Month : {release_date.month}")
print(f"Day   : {release_date.day}")

print("-" * 20)

# 2. Get today's date
# Use the class method today()
today = date.today()
print(f"Today's Date : {today}")

# Date comparison is also possible
days_left = (release_date - today).days
print(f"Days until release : {days_left} days")

Execution Result

Release Date (date): 2025-11-20
--------------------
Year  : 2025
Month : 11
Day   : 20
--------------------
Today's Date : 2025-12-15
Days until release : -25 days

(Note: “Today’s Date” and “Days until release” will change based on when the code is executed.)

Explanation

Difference from the datetime Type

While the datetime type holds “date + time,” the date type holds purely “date” information.

Therefore, attributes like d.hour or d.minute do not exist, and attempting to access them will result in an AttributeError.

Necessity of Zero-Padding

The retrieved month and day are integers (e.g., 1, 5). If you want to display them with zero-padding like “01” or “05,” use string formatting.

# Example: Formatting as 2025-01-05
print(f"{release_date.year}-{release_date.month:02}-{release_date.day:02}")
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次