-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
Sascha Kirch
  • 466
  • 2
  • 3
  • 19
Optimus
  • 24
  • 8

4 Answers4

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()
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
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()
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

You can use datetime to get current time.

import datetime
datetime.datetime.now()
Nisarg Shah
  • 379
  • 1
  • 10
0

#This is how I usually do this

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