w3resource

Python: Get the current time


4. Current Time Fetcher

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.

For more Practice: Solve these Related Problems:

  • Write a Python program to display the current local time in "HH:MM:SS" format and then print the corresponding UTC time.
  • Write a Python script that retrieves the current time and formats it as a 12-hour clock with leading zeros.
  • Write a Python program to fetch the current time and then display the time in both digital and analog clock style (text-based).
  • Write a Python script to get the current time, then convert and display it in military (24-hour) format with microseconds.

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.