Python datetime today Function

The datetime.today function in Python's datetime module returns the current local date and time. This function is useful for capturing the present moment in your programs, including both date and time information, similar to the datetime.now function.

Table of Contents

  1. Introduction
  2. datetime.today Function Syntax
  3. Examples
    • Basic Usage
    • Formatting Current Date and Time
  4. Real-World Use Case
  5. Conclusion

Introduction

The datetime.today function in Python's datetime module retrieves the current local date and time as a datetime object. It is particularly useful for timestamping events, logging, and any application where you need to record the current date and time.

datetime.today Function Syntax

Here is how you use the datetime.today function:

from datetime import datetime
current_datetime = datetime.today()

Parameters:

  • The datetime.today function does not take any parameters.

Returns:

  • A datetime object representing the current local date and time.

Examples

Basic Usage

Here is an example of how to use datetime.today.

Example

from datetime import datetime

# Getting the current local date and time
current_datetime = datetime.today()
print("Current local date and time:", current_datetime)

Output:

Current local date and time: 2024-07-23 20:35:03.044610

Formatting Current Date and Time

This example shows how to format the current date and time using the strftime method of the datetime object.

Example

from datetime import datetime

# Getting the current local date and time
current_datetime = datetime.today()

# Formatting the current date and time
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted current date and time:", formatted_datetime)

Output:

Formatted current date and time: 2024-07-23 20:35:03

Real-World Use Case

Timestamping Events

In real-world applications, the datetime.today function can be used to timestamp events, making it useful for logging and tracking the timing of actions.

Example

from datetime import datetime
import time

def log_event(event):
    timestamp = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] Event: {event}")

# Example usage
log_event("Start process")
time.sleep(2)
log_event("End process")

Output:

[2024-07-23 20:35:03] Event: Start process
[2024-07-23 20:35:05] Event: End process

Conclusion

The datetime.today function provides the current local date and time as a datetime object, making it useful for timestamping, logging, and any application requiring the current date and time.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare