Skip to main content

How to get the current time in Python

How to get the current time in Python.

Here's a step-by-step tutorial on how to get the current time in Python:

Step 1: Import the necessary module To get the current time in Python, you need to import the datetime module. This module provides various classes and functions to work with dates and times.

import datetime

Step 2: Get the current time Once you have imported the datetime module, you can use the datetime.now() function to get the current time. This function returns a datetime object representing the current date and time.

current_time = datetime.datetime.now()

Step 3: Extract the time components The datetime object returned by datetime.now() contains various attributes like year, month, day, hour, minute, second, etc. To get the current time, you can extract the hour, minute, and second components using the hour, minute, and second attributes.

current_hour = current_time.hour
current_minute = current_time.minute
current_second = current_time.second

Step 4: Print the current time Finally, you can print the current time using the extracted time components. You can format the output as per your preference using string formatting.

print("Current time: {}:{}:{}".format(current_hour, current_minute, current_second))

Here's the complete code:

import datetime

current_time = datetime.datetime.now()
current_hour = current_time.hour
current_minute = current_time.minute
current_second = current_time.second

print("Current time: {}:{}:{}".format(current_hour, current_minute, current_second))

This code will display the current time in the format hour:minute:second. You can run this code in any Python environment to get the current time.