-3

How do I get and print the current time in Python?

I'm following this Tutorial and want to print the current time in my python script. I can not reproduce what is thought in the toturial. The current time is not printed.
Here is my current code for the Python script:

main.py:

def printTime(): print("The time is"+time+"right now"); printTime(); 

I want to achieve is

  • That the time variable is a variable that equals the current time
  • To find a way to get the current time printed
1
  • 3
    Copy paste the title of your question in the web search provider of your choice. Commented Mar 3, 2021 at 15:52

4 Answers 4

4

Just use datetime.now() method of datetime module:-

import datetime time=datetime.datetime.now() def printTime(): print("The time is",time,"right now"); printTime() 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use datetime.now() from datetime module to get the current date and time like this,

import datetime current_date_time = datetime.datetime.now() 

Plugging in this to your function,

import datetime def printTime(): current_date_time = datetime.datetime.now() print(f"The time is {current_date_time} right now") printTime() 

If you are not interested in the date part and only want the time part, you can extract time component from the datetime object like this

import datetime def printTime(): current_time = datetime.datetime.now().time() # get only time component print(f"The time is {current_time} right now") printTime() 

3 Comments

Thanks for answering my question and it was very quick as well
Really doubt that "The time is" + current_date_time is going to work.
@Marco Bonelli fixed that now......
1

You can use datetime to get current time.

import datetime datetime.datetime.now() 

Comments

0

#This is how I usually do this

import time; CurrentTime= time.asctime( time.localtime(time.time()) ) print ("Date/Time:", CurrentTime) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.