Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Mastering Python’s datetime Module: Dates, Times, Timedelta & Strftime Explained

Python’s datetime library offers a robust set of tools for manipulating dates, times, and time intervals. By working with objects rather than raw strings or timestamps, developers can perform precise calculations and formatting with confidence.

Key datetime Classes

Getting Started: Importing and Instantiating

Before any manipulation, import the needed classes:

from datetime import date, time, datetime, timedelta

Instantiate a date object:

today = date.today()
print(today)  # e.g., 2024-04-19

Current Date and Time

The datetime.now() method returns the current local date and time:

now = datetime.now()
print(now)  # 2024-04-19 14:35:12.123456

To extract just the time component:

current_time = now.time()
print(current_time)  # 14:35:12.123456

Formatting Output with strftime

The strftime method converts datetime objects to human‑readable strings using format codes:

now.strftime("%Y-%m-%d %H:%M:%S")
# "2024-04-19 14:35:12"

Common directives include:

Examples:

# 12‑hour format with AM/PM
print(now.strftime("%I:%M:%S %p"))
# 24‑hour format
print(now.strftime("%H:%M"))

Working with timedelta

A timedelta represents a span of time. It supports arithmetic with dates and datetimes:

# Create a timedelta of 365 days
one_year = timedelta(days=365)
# One year from today
future_date = datetime.now() + one_year
print(future_date)

Calculating days until an event (e.g., New Year):

today = date.today()
new_year = date(today.year, 1, 1)
if new_year < today:
    new_year = date(today.year + 1, 1, 1)
    print("New Year is in", (new_year - today).days, "days")
else:
    print("New Year is in", (new_year - today).days, "days")

Putting It All Together

Below is a concise, ready‑to‑run script that demonstrates the core features:

from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
print("Now:", now)

# Format examples
print("ISO format:", now.strftime("%Y-%m-%d %H:%M:%S"))
print("12‑hour time:", now.strftime("%I:%M:%S %p"))

# Timedelta operations
one_week = timedelta(weeks=1)
print("One week from now:", now + one_week)

# Days until New Year
today = date.today()
new_year = date(today.year + (today < date(today.year, 1, 1)), 1, 1)
print("Days until New Year:", (new_year - today).days)

Summary

Python’s datetime module equips developers with powerful, type‑safe tools for date and time manipulation:

These tools are essential for tasks ranging from simple timestamping to complex scheduling logic.

Python

  1. Mastering Python datetime: Practical Guide to Dates, Times, and Timezones
  2. Python: Retrieve Current Time and Timezone Data with Ease
  3. Master Python’s str.count(): How to Count Characters & Substrings with Examples
  4. Master Python `format()` Strings with Clear Examples
  5. Python round() Function Explained with Practical Examples
  6. Mastering Python's map() Function: Syntax, Examples, and Best Practices
  7. Python timeit() – Measuring Execution Time with Practical Examples
  8. Python list.count(): Expert Guide with Practical Examples
  9. Python Module Importing – A Practical Guide with Examples
  10. Mastering Dates & Times in Python: A Practical Guide