[Python] Converting Between Date and String: strptime and strftime

In Python, it is very common to convert “strings to dates” (for reading from CSVs or logs) and “dates to strings” (for screen display).

While you use the strptime and strftime methods just like with the datetime type, there are specific steps required when handling the date type (such as using the .date() method).

目次

Implementation Example: Converting Date Formats

In this scenario, we read a slash-separated date string "2025/10/12", process it as a date object, and then convert it to a hyphen-separated string "2025-10-12" for output.

Source Code

from datetime import datetime, date

# --- 1. Converting String to date Object ---
input_str = "2025/10/12"

# Step 1: Convert to datetime type using datetime.strptime(string, format)
# %Y: Year (4 digits), %m: Month, %d: Day
dt_obj = datetime.strptime(input_str, "%Y/%m/%d")

# Step 2: Use the .date() method to discard time info and get the date type
d_obj = dt_obj.date()

print(f"Converted Type : {type(d_obj)}")
print(f"Date Data      : {d_obj}")

print("-" * 30)

# --- 2. Converting date Object to String ---
# Use strftime(format) to convert to a string in any format
# Here, we convert to "YYYY-MM-DD" format
output_str = d_obj.strftime("%Y-%m-%d")

print(f"Output String  : {output_str}")
print(f"Output Type    : {type(output_str)}")

Execution Result

Converted Type : <class 'datetime.date'>
Date Data      : 2025-10-12
------------------------------
Output String  : 2025-10-12
Output Type    : <class 'str'>

Explanation

String → date (strptime)

datetime.strptime() always returns a datetime object (containing both date and time). Therefore, if you want to handle it as a date type (date only), you must call the .date() method at the end to convert it.

Syntax: datetime.strptime(date_string, format).date()

date → String (strftime)

By using the strftime() method available on the date object, you can convert it to a string with a specified format.

Syntax: date_object.strftime(format)

Common Formats:

  • %Y/%m/%d → 2025/10/12
  • %Y-%m-%d → 2025-10-12
  • %d %B %Y → 12 October 2025

Supplement: Using ISO Format

For standard ISO 8601 formats (hyphen-separated like "2025-10-12"), you can use the faster date.fromisoformat() method (available in Python 3.7+).

d = date.fromisoformat("2025-10-12")
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次