[Python] Getting the Current Date: Usage of date.today() and String Conversion

If you want to get only “today’s date” without time information (hours, minutes, seconds) in Python, use the today() method of the date class in the datetime module.

This article explains how to retrieve the current date and convert it into a string format suitable for filenames or logs.

目次

Implementation Example: Getting the Date for a Daily Report

In this scenario, we retrieve “today’s” date and use it to create a title string for a report.

Source Code

Python

from datetime import date

# 1. Get today's date
# date.today() returns a date object with the current date (local time)
today = date.today()

# 2. Convert date to string
# Use strftime(format) to format it into any style
# %Y: Year (4 digits), %m: Month (2 digits), %d: Day (2 digits)
date_string = today.strftime("%Y-%m-%d")

# Another format example (e.g., localized format)
# Note: For non-ASCII characters, ensure your environment supports them
japanese_date_string = today.strftime("%Y年%m月%d日")

# Output results
print(f"Acquired Object   : {today}")
print(f"Type              : {type(today)}")
print("-" * 30)
print(f"ISO Format String : {date_string}")
print(f"Japanese Format   : {japanese_date_string}")

Execution Result

Plaintext

Acquired Object   : 2025-12-16
Type              : <class 'datetime.date'>
------------------------------
ISO Format String : 2025-12-16
Japanese Format   : 2025年12月16日

Explanation

date.today()

The date.today() class method generates and returns a date object containing the Year, Month, and Day based on the system’s date settings. Unlike datetime.now(), it does not hold time data (hours, minutes, seconds).

Distinction from datetime.now()

  • date.today(): Use this when time is unnecessary, such as for “Dates of Birth,” “Anniversaries,” or simply “Today’s Date.”
  • datetime.now(): Use this when precise time is required, such as for “Log Timestamps” or “Measuring Processing Time.”
    • Note: If you need to extract only the date from a datetime object, you can use the .date() method (e.g., datetime.now().date()).
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次