The time and datetime Modules for Tracking

🏷️ Modules and Imports / Built-in Modules for Engineers

🎯 Context Introduction

When working with scripts that run over long periods, schedule tasks, or need to log when events happen, you need reliable ways to track time. Python provides two essential built-in modules for this purpose: time and datetime. The time module works with timestamps and basic timing operations, while datetime gives you more human-friendly date and time objects. Together, they help you measure execution duration, add delays, format timestamps for logs, and schedule recurring tasks.


⚙️ The time Module – Working with Timestamps

The time module is your go-to for measuring how long something takes or adding pauses in your script. It works primarily with epoch timestamps (seconds since January 1, 1970).

Key functions you will use most often:

  • time.time() – Returns the current timestamp as a float (seconds since epoch). Use this to measure elapsed time by capturing it before and after an operation.
  • time.sleep(seconds) – Pauses your script for a given number of seconds. Useful for rate-limiting API calls or waiting between retries.
  • time.ctime() – Converts a timestamp into a readable string like "Mon Mar 10 12:30:45 2025". If called with no argument, it returns the current time.

Common use case – measuring execution time:

  • Capture start_time = time.time() before your code runs.
  • Run your code or function.
  • Capture end_time = time.time() after it finishes.
  • Calculate elapsed = end_time - start_time to get seconds.
  • Print the result formatted to two decimal places.

Common use case – adding delays:

  • Call time.sleep(5) to pause execution for 5 seconds.
  • Use time.sleep(0.5) for half-second delays between retries.

📅 The datetime Module – Human-Readable Dates and Times

The datetime module is more powerful for working with dates, times, and time arithmetic. It provides objects you can compare, format, and manipulate easily.

Core classes you will use:

  • datetime.datetime – Combines date and time into one object (year, month, day, hour, minute, second, microsecond).
  • datetime.date – Represents a date only (year, month, day).
  • datetime.time – Represents a time only (hour, minute, second, microsecond).
  • datetime.timedelta – Represents a duration or difference between two dates/times.

Key functions and methods:

  • datetime.datetime.now() – Returns the current local date and time as a datetime object.
  • datetime.datetime.utcnow() – Returns the current UTC date and time.
  • .strftime(format) – Converts a datetime object into a formatted string (string from time).
  • .strptime(date_string, format) – Parses a string into a datetime object (string parse time).

Common format codes for strftime and strptime:

  • %Y – Four-digit year (2025)
  • %m – Two-digit month (01 to 12)
  • %d – Two-digit day (01 to 31)
  • %H – Two-digit hour in 24-hour format (00 to 23)
  • %M – Two-digit minute (00 to 59)
  • %S – Two-digit second (00 to 59)

Common use case – getting the current timestamp for logs:

  • Call now = datetime.datetime.now() to get the current time.
  • Format it with now.strftime("%Y-%m-%d %H:%M:%S") to get a string like "2025-03-10 14:30:00".
  • Use this string in your log messages.

Common use case – calculating time differences:

  • Create two datetime objects: start_time = datetime.datetime.now() and end_time = datetime.datetime.now() after your operation.
  • Subtract them: duration = end_time - start_time.
  • Access duration.total_seconds() to get the total seconds as a float.

🛠️ Comparison: time vs datetime

Feature time Module datetime Module
Primary data type Timestamps (floats) Objects (datetime, date, time)
Human readability Low – needs conversion High – built-in formatting
Time arithmetic Manual subtraction of floats Use timedelta objects
Date manipulation Limited Full support (add days, months)
Formatting output time.ctime() or time.strftime() .strftime() method
Parsing strings time.strptime() datetime.strptime()
Best for Measuring durations, delays, simple timing Logging timestamps, scheduling, date math

🕵️ Practical Patterns for Engineers

Pattern 1 – Logging with timestamps:

  • Get current time using datetime.datetime.now().
  • Format it with .strftime("%Y-%m-%d %H:%M:%S").
  • Build your log message: f"[{timestamp}] INFO: Task completed successfully".
  • Write this to a file or print it.

Pattern 2 – Measuring how long a task takes:

  • Use time.time() before and after the task.
  • Calculate elapsed = end - start.
  • Print f"Task took {elapsed:.2f} seconds".
  • For more precision, use time.perf_counter() instead of time.time().

Pattern 3 – Running a task every N seconds:

  • Use a while True loop.
  • Inside the loop, run your task.
  • Call time.sleep(interval) where interval is your desired delay in seconds.
  • Add a break condition to stop the loop when needed.

Pattern 4 – Scheduling a task at a specific time:

  • Define your target time as a string: target = "14:30:00".
  • Parse it: target_time = datetime.datetime.strptime(target, "%H:%M:%S").time().
  • In a loop, get now = datetime.datetime.now().time().
  • Compare now >= target_time to trigger your task.
  • Add a small time.sleep(1) to avoid busy-waiting.

✅ Summary Checklist

  • Use time.time() for simple duration measurements.
  • Use time.sleep() to add pauses between operations.
  • Use datetime.datetime.now() for human-readable timestamps.
  • Use .strftime() to format dates for logs and filenames.
  • Use .strptime() to parse date strings from configuration files.
  • Use timedelta objects for date arithmetic (add days, subtract hours).
  • Prefer datetime for most scheduling and logging tasks.
  • Use time for lightweight timing and delays.

Both modules are built-in, so no installation is needed. Start with datetime for most date-related work, and reach for time when you need simple counters or delays. Together, they give you full control over time in your Python scripts.


The time and datetime modules provide functions for working with time values, timestamps, and calendar dates in Python.


⏱️ Example 1: Getting the current timestamp with time.time()

This example shows how to get the current Unix timestamp (seconds since January 1, 1970).

import time

current_timestamp = time.time()
print(current_timestamp)

📤 Output: 1700000000.123456 (value will vary each run)


📅 Example 2: Getting the current date and time with datetime.now()

This example shows how to get the current date and time as a readable datetime object.

from datetime import datetime

current_datetime = datetime.now()
print(current_datetime)

📤 Output: 2024-11-14 15:30:45.123456 (value will vary each run)


⏳ Example 3: Measuring elapsed time with time.perf_counter()

This example shows how to measure how long a block of code takes to execute.

import time

start_time = time.perf_counter()

# Simulate a short delay
time.sleep(1.5)

end_time = time.perf_counter()
elapsed = end_time - start_time
print(elapsed)

📤 Output: 1.500123456 (value will vary slightly)


🗓️ Example 4: Formatting a datetime object into a readable string

This example shows how to convert a datetime object into a custom string format using strftime.

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")
print(formatted_date)
print(formatted_time)

📤 Output: 2024-11-14
📤 Output: 15:30:45


🔄 Example 5: Converting a string into a datetime object with strptime

This example shows how to parse a date string into a datetime object for calculations.

from datetime import datetime

date_string = "2024-12-25 10:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)
print(type(parsed_date))

📤 Output: 2024-12-25 10:30:00
📤 Output:


Comparison Table: time vs datetime

Feature time module datetime module
Purpose Low-level time functions (timestamps, delays) High-level date and time objects
Current time time.time() returns a float (Unix timestamp) datetime.now() returns a datetime object
Formatting Limited to time.strftime() Full strftime() and strptime() support
Measuring duration time.perf_counter() for high-precision timing datetime subtraction returns timedelta
Date arithmetic Not supported directly Full support with timedelta objects
Best for engineers Timing code execution, delays Logging dates, scheduling, date math

🎯 Context Introduction

When working with scripts that run over long periods, schedule tasks, or need to log when events happen, you need reliable ways to track time. Python provides two essential built-in modules for this purpose: time and datetime. The time module works with timestamps and basic timing operations, while datetime gives you more human-friendly date and time objects. Together, they help you measure execution duration, add delays, format timestamps for logs, and schedule recurring tasks.


⚙️ The time Module – Working with Timestamps

The time module is your go-to for measuring how long something takes or adding pauses in your script. It works primarily with epoch timestamps (seconds since January 1, 1970).

Key functions you will use most often:

  • time.time() – Returns the current timestamp as a float (seconds since epoch). Use this to measure elapsed time by capturing it before and after an operation.
  • time.sleep(seconds) – Pauses your script for a given number of seconds. Useful for rate-limiting API calls or waiting between retries.
  • time.ctime() – Converts a timestamp into a readable string like "Mon Mar 10 12:30:45 2025". If called with no argument, it returns the current time.

Common use case – measuring execution time:

  • Capture start_time = time.time() before your code runs.
  • Run your code or function.
  • Capture end_time = time.time() after it finishes.
  • Calculate elapsed = end_time - start_time to get seconds.
  • Print the result formatted to two decimal places.

Common use case – adding delays:

  • Call time.sleep(5) to pause execution for 5 seconds.
  • Use time.sleep(0.5) for half-second delays between retries.

📅 The datetime Module – Human-Readable Dates and Times

The datetime module is more powerful for working with dates, times, and time arithmetic. It provides objects you can compare, format, and manipulate easily.

Core classes you will use:

  • datetime.datetime – Combines date and time into one object (year, month, day, hour, minute, second, microsecond).
  • datetime.date – Represents a date only (year, month, day).
  • datetime.time – Represents a time only (hour, minute, second, microsecond).
  • datetime.timedelta – Represents a duration or difference between two dates/times.

Key functions and methods:

  • datetime.datetime.now() – Returns the current local date and time as a datetime object.
  • datetime.datetime.utcnow() – Returns the current UTC date and time.
  • .strftime(format) – Converts a datetime object into a formatted string (string from time).
  • .strptime(date_string, format) – Parses a string into a datetime object (string parse time).

Common format codes for strftime and strptime:

  • %Y – Four-digit year (2025)
  • %m – Two-digit month (01 to 12)
  • %d – Two-digit day (01 to 31)
  • %H – Two-digit hour in 24-hour format (00 to 23)
  • %M – Two-digit minute (00 to 59)
  • %S – Two-digit second (00 to 59)

Common use case – getting the current timestamp for logs:

  • Call now = datetime.datetime.now() to get the current time.
  • Format it with now.strftime("%Y-%m-%d %H:%M:%S") to get a string like "2025-03-10 14:30:00".
  • Use this string in your log messages.

Common use case – calculating time differences:

  • Create two datetime objects: start_time = datetime.datetime.now() and end_time = datetime.datetime.now() after your operation.
  • Subtract them: duration = end_time - start_time.
  • Access duration.total_seconds() to get the total seconds as a float.

🛠️ Comparison: time vs datetime

Feature time Module datetime Module
Primary data type Timestamps (floats) Objects (datetime, date, time)
Human readability Low – needs conversion High – built-in formatting
Time arithmetic Manual subtraction of floats Use timedelta objects
Date manipulation Limited Full support (add days, months)
Formatting output time.ctime() or time.strftime() .strftime() method
Parsing strings time.strptime() datetime.strptime()
Best for Measuring durations, delays, simple timing Logging timestamps, scheduling, date math

🕵️ Practical Patterns for Engineers

Pattern 1 – Logging with timestamps:

  • Get current time using datetime.datetime.now().
  • Format it with .strftime("%Y-%m-%d %H:%M:%S").
  • Build your log message: f"[{timestamp}] INFO: Task completed successfully".
  • Write this to a file or print it.

Pattern 2 – Measuring how long a task takes:

  • Use time.time() before and after the task.
  • Calculate elapsed = end - start.
  • Print f"Task took {elapsed:.2f} seconds".
  • For more precision, use time.perf_counter() instead of time.time().

Pattern 3 – Running a task every N seconds:

  • Use a while True loop.
  • Inside the loop, run your task.
  • Call time.sleep(interval) where interval is your desired delay in seconds.
  • Add a break condition to stop the loop when needed.

Pattern 4 – Scheduling a task at a specific time:

  • Define your target time as a string: target = "14:30:00".
  • Parse it: target_time = datetime.datetime.strptime(target, "%H:%M:%S").time().
  • In a loop, get now = datetime.datetime.now().time().
  • Compare now >= target_time to trigger your task.
  • Add a small time.sleep(1) to avoid busy-waiting.

✅ Summary Checklist

  • Use time.time() for simple duration measurements.
  • Use time.sleep() to add pauses between operations.
  • Use datetime.datetime.now() for human-readable timestamps.
  • Use .strftime() to format dates for logs and filenames.
  • Use .strptime() to parse date strings from configuration files.
  • Use timedelta objects for date arithmetic (add days, subtract hours).
  • Prefer datetime for most scheduling and logging tasks.
  • Use time for lightweight timing and delays.

Both modules are built-in, so no installation is needed. Start with datetime for most date-related work, and reach for time when you need simple counters or delays. Together, they give you full control over time in your Python scripts.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

The time and datetime modules provide functions for working with time values, timestamps, and calendar dates in Python.


⏱️ Example 1: Getting the current timestamp with time.time()

This example shows how to get the current Unix timestamp (seconds since January 1, 1970).

import time

current_timestamp = time.time()
print(current_timestamp)

📤 Output: 1700000000.123456 (value will vary each run)


📅 Example 2: Getting the current date and time with datetime.now()

This example shows how to get the current date and time as a readable datetime object.

from datetime import datetime

current_datetime = datetime.now()
print(current_datetime)

📤 Output: 2024-11-14 15:30:45.123456 (value will vary each run)


⏳ Example 3: Measuring elapsed time with time.perf_counter()

This example shows how to measure how long a block of code takes to execute.

import time

start_time = time.perf_counter()

# Simulate a short delay
time.sleep(1.5)

end_time = time.perf_counter()
elapsed = end_time - start_time
print(elapsed)

📤 Output: 1.500123456 (value will vary slightly)


🗓️ Example 4: Formatting a datetime object into a readable string

This example shows how to convert a datetime object into a custom string format using strftime.

from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")
print(formatted_date)
print(formatted_time)

📤 Output: 2024-11-14
📤 Output: 15:30:45


🔄 Example 5: Converting a string into a datetime object with strptime

This example shows how to parse a date string into a datetime object for calculations.

from datetime import datetime

date_string = "2024-12-25 10:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed_date)
print(type(parsed_date))

📤 Output: 2024-12-25 10:30:00
📤 Output:


Comparison Table: time vs datetime

Feature time module datetime module
Purpose Low-level time functions (timestamps, delays) High-level date and time objects
Current time time.time() returns a float (Unix timestamp) datetime.now() returns a datetime object
Formatting Limited to time.strftime() Full strftime() and strptime() support
Measuring duration time.perf_counter() for high-precision timing datetime subtraction returns timedelta
Date arithmetic Not supported directly Full support with timedelta objects
Best for engineers Timing code execution, delays Logging dates, scheduling, date math