Skillversitas

Date & Time

Python provides the time and datetime modules for handling date- and time-related operations.

The datetime module is the most commonly used because it provides classes such as date, time, datetime, timedelta, and timezone. The datetime class combines date and time information at the same time. Meanwhile, timedelta represents a time difference and can be used for arithmetic operations such as adding or subtracting days, hours, or minutes.

The strftime() method is very useful for formatting a date into a string in various formats, for example displaying the weekday name or an international date format. Conversely, strptime() can convert a string into a datetime object for further processing.

Code Example

from datetime import datetime, timedelta

# Current time
now = datetime.now()
print(now.strftime("%d/%m/%Y %H:%M"))
# Example: 25/01/2025 14:30

# Create a specific date
birth_date = datetime(2000, 1, 15)
print("Born:", birth_date.strftime("%A, %d %B %Y"))
# Born: Saturday, 15 January 2000

# Date operations
tomorrow = now + timedelta(days=1)
difference = now - birth_date
print("Age (days):", difference.days)

Code Explanation

  1. Import: from datetime import datetime, timedelta imports the two main classes — datetime for date-time objects and timedelta for time differences.
  2. Current time: datetime.now() gets the current system time. The strftime("%d/%m/%Y %H:%M") method formats it as a string in the format: day/month/year hour:minute.
  3. Specific date: datetime(2000, 1, 15) creates a datetime object for January 15, 2000. strftime("%A, %d %B %Y") displays the weekday name, date, month name, and year.
  4. Date operations: now + timedelta(days=1) computes tomorrow's date. Subtracting two datetime objects produces a timedelta object; access the .days attribute to get the number of days.

Everyday Example

A library book-borrowing application needs to compute due dates and late fees.

from datetime import datetime, timedelta

borrow_date = datetime(2025, 1, 10)
borrow_days = 7  # days
due_date = borrow_date + timedelta(days=borrow_days)
return_date = datetime(2025, 1, 20)

if return_date > due_date:
    late_days = (return_date - due_date).days
    fine = late_days * 1000
    print(f"{late_days} days late, fine ${fine:,}")
else:
    print("On time")
# Output: 3 days late, fine $3,000

Summary

The datetime module provides complete tools for date and time manipulation in Python. With datetime, timedelta, and strftime, you can create, compute differences, and format dates with ease. These features are essential for time-related applications such as lending systems, reminders, or logging.