zaro

How to get current time in Python?

Published in Python Datetime 2 mins read

To get the current time in Python, you can use the datetime module. Here's a breakdown of how to do it, along with examples:

Getting the Current Time Using datetime

The core method for obtaining the current time is by using the datetime.now() function from the datetime module. This function returns a datetime object that contains both the date and time.

Steps:

  1. Import datetime: Start by importing the datetime class from the datetime module.
    from datetime import datetime
  2. Get the current time: Use datetime.now() to get the current date and time.
    current_time = datetime.now()
  3. Print the current time: Print the current_time object to see the result.

Code Example:

from datetime import datetime

current_time = datetime.now()

print(current_time)           # Output: Full date and time e.g., 2024-01-27 10:30:45.123456
print(current_time.time())    # Output: Time only e.g., 10:30:45.123456
print(current_time.date())    # Output: Date only e.g., 2024-01-27

Explanation

  • datetime.now(): This function captures the current local date and time as a datetime object.
  • Printing current_time: Directly printing current_time displays the full date and time information, including year, month, day, hour, minute, second, and microseconds.
  • current_time.time(): This extracts and prints only the time portion of the datetime object, showing the hour, minute, second, and microseconds.
  • current_time.date(): This extracts and prints only the date portion of the datetime object, showing the year, month, and day.

Practical Uses

  • Logging: Recording timestamps for events in your application logs.
  • Scheduling: Running tasks at specific times or with certain delays.
  • Time Calculations: Performing time-based calculations or comparisons.
  • User Interface: Displaying the current time to users.

Summary

Method Description Example Output
datetime.now() Gets the current date and time as a datetime object 2024-01-27 10:30:45.123456
datetime.now().time() Gets the current time only 10:30:45.123456
datetime.now().date() Gets the current date only 2024-01-27

By utilizing the datetime module and its associated functions, obtaining the current time in Python is a straightforward task, with many uses across various applications.