[Python] 4 Key Types of the datetime Module and How to Use Them

Python’s standard datetime module allows you to handle dates and times. It consists of four main data types (classes) that should be used according to your purpose.

Understanding the role and differences of each is essential for accurately implementing schedule calculations and log recording.

目次

List of Key Data Types and Roles

Data Type (Class)RoleInformation HeldExample
dateHandles dates onlyYear, Month, Day2025-12-15 (Birthdays, Anniversaries)
timeHandles time onlyHour, Minute, Second, Microsecond14:30:00 (Start time, Fixed time)
datetimeHandles both date and timeYMD + HMS2025-12-15 09:00:00 (Logs, Schedules)
timedeltaHandles duration/differenceDays, Seconds, etc.7 days (1 week later, Elapsed time)

Implementation Example: Calculating a Project Schedule

Here is a practical code example combining these four types.

The scenario involves getting the “current date and time” and adding a specific “period (timedelta)” to calculate a deadline.

Source Code

from datetime import date, time, datetime, timedelta

# --- 1. datetime: Get current date and time ---
# Get the system's current time
current_dt = datetime.now()
print(f"Current Date/Time (datetime): {current_dt}")

# --- 2. date: Create a specific date ---
# Create an object by specifying year, month, and day
# Example: Project kickoff date
kickoff_date = date(2025, 4, 1)
print(f"Start Date (date)           : {kickoff_date}")

# --- 3. time: Specify a specific time ---
# Specify hour, minute, and second
# Example: Time for a daily meeting
meeting_time = time(9, 30, 0) # 09:30:00
print(f"Meeting Time (time)         : {meeting_time}")

# --- 4. timedelta: Date calculation (Addition/Subtraction) ---
# Represents "duration" or "difference" in time
# Example: Project duration is "2 weeks and 3 days"
project_duration = timedelta(weeks=2, days=3)

# Add duration to start date to calculate end date
# date type + timedelta type = date type
end_date = kickoff_date + project_duration

print("-" * 30)
print(f"Project Duration            : {project_duration}")
print(f"Scheduled End Date          : {end_date}")

# --- Bonus: Calculating the difference between dates ---
# Subtracting dates returns a timedelta (duration)
days_until_kickoff = kickoff_date - date.today()
print(f"Days until kickoff          : {days_until_kickoff.days} days")

Execution Result

Current Date/Time (datetime): 2025-12-15 10:00:00.123456
Start Date (date)           : 2025-04-01
Meeting Time (time)         : 09:30:00
------------------------------
Project Duration            : 17 days, 0:00:00
Scheduled End Date          : 2025-04-18
Days until kickoff          : -258 days

(Note: Execution results depend on when the code is run. The “Days until kickoff” example above shows a negative value as a past date was simulated.)

Explanation

  • Arithmetic Compatibility: By adding or subtracting a timedelta to a date or datetime object, you can easily calculate values like “N days later” or “N hours ago.”
  • Calculating Differences: Subtracting two date objects (or two datetime objects) results in a timedelta object, representing the elapsed time.
  • Caution: You cannot directly add or subtract a date object (date only) and a datetime object (date + time). You must convert one of them to match the other type before calculation.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

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

目次