[Python] Getting Current Date/Time and Formatting as String

When recording log timestamps or including dates in filenames in Python, the standard pattern is to combine the now() and strftime() methods of the datetime class.

This article explains how to get the current date and time (Year, Month, Day, Hour, Minute, Second) and convert it into a readable string format like “2025-12-15 10:30:00”.

目次

Implementation Example: Recording Execution Time

In this scenario, we capture the timing when a batch process or script is executed and display it in a standard date format.

Source Code

from datetime import datetime

# 1. Get current date/time (datetime object)
# Retrieves the system's local time
current_timestamp = datetime.now()

# 2. Convert datetime object to string (Formatting)
# Use strftime(format_string)
# %Y: Year (4 digits), %m: Month (0-padded), %d: Day (0-padded)
# %H: Hour (24-hour), %M: Minute, %S: Second
formatted_date = current_timestamp.strftime("%Y-%m-%d %H:%M:%S")

# Output results
print(f"Acquired Object : {current_timestamp}")
print(f"Type            : {type(current_timestamp)}")
print("-" * 40)
print(f"After Formatting: {formatted_date}")
print(f"Type            : {type(formatted_date)}")

Execution Result

Acquired Object : 2025-12-15 18:05:30.123456
Type            : <class 'datetime.datetime'>
----------------------------------------
After Formatting: 2025-12-15 18:05:30
Type            : <class 'str'>

Explanation

datetime.now()

datetime.now() returns a datetime object containing the current local time of the system where the program is running. While this object contains the raw data needed for calculations, it must be converted to a string for display or file saving.

strftime() Method

The strftime (String Format Time) method converts a datetime object into a string according to a specified format code.

Commonly Used Specifiers:

SpecifierMeaningExample
%YYear (4 digits)2025
%mMonth (0-padded)01, 12
%dDay (0-padded)05, 31
%HHour (24-hour clock)09, 23
%MMinute00, 59
%SSecond05, 59
%ADay of the week (English)Sunday, Monday

By combining these, you can create date strings in any format suitable for your needs, such as "%Y/%m/%d" or "%H:%M".

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次