w3resource

Python: Get the current time


Write a Python program to get the current time.

Sample Solution:

Python Code:

# Import the datetime module
import datetime

# Get the current date and time using datetime.now() and then retrieve the time component using time()
# Print the current time
print(datetime.datetime.now().time())

Output:

18:08:21.552122 

Explanation:

In the exercise above,

  • The code imports the "datetime" module, which provides functionalities to work with dates and times.
  • Printing Current Time:
    • It utilizes the "datetime.datetime.now()" function to get the current date and time.
    • Then, it retrieves only the time component of the current date and time using the "time()" method.
    • Finally, it prints the current time using the "print()" function.

Flowchart:

Flowchart: Get the current time.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to convert a string to datetime.
Next: Write a Python program to subtract five days from current date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.