w3resource

Python: Get the current time

Python datetime: Exercise-4 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/date-time-exercise/python-date-time-exercise-4.php