Get current datetime, date and time

To determine the current date and time, Python provides us with various methods via the datetime module.

With the now() method we get a datetime object with current date and time. With the today() method we get a date object with the current date. The strftime() method formats a datetime object with a specified formatting

import datetime

current_datetime = datetime.datetime.now()
current_date = datetime.date.today()
current_time = current_datetime.strftime("%H:%M:%S")

print(current_datetime)
print(current_date)
print(current_time)
Code Explanation
  1. Importing the datetime module: This module provides classes for manipulating dates and times. It’s a comprehensive module packed with methods for date, time, and duration arithmetic.
  2. Getting the current datetime: The datetime.datetime.now() method retrieves the current local datetime with both date and time components, down to the microsecond.
  3. Getting the current date: The datetime.date.today() method fetches the current local date. This method returns only the date component (year, month, day), without any time information.
  4. Formatting the current time: The strftime("%H:%M:%S") method is used to format the time component of the current_datetime object into a string formatted as hours, minutes, and seconds. This method is particularly useful for displaying time in a readable format or for logging purposes where only the time is necessary.
  5. Printing results:
    • The current_datetime is printed, displaying the full date and time down to the microsecond. This is useful for timestamps in logging or for operations where precise time tracking is required.
    • The current_date is printed, showing only the date. This is often used for date stamps on reports, logs, or any process that requires recording or displaying the date only.
    • The current_time is printed in the “HH:MM:SS” format, showing a human-readable time.
Output
2022-12-09 09:51:30.813294
2022-12-09
09:51:30