How do I Get the Current Time in Python?

We can get the current time through the datetime module and strftime() function. The datetime module provides the current time and strftime() function represents it. Let’s get started.

from datetime import datetime

Above line imports datetime class from datetime module.

# get the current date and time
currentDay = datetime.now()
print(‘currentDay’)
# Output: 2022-11-08 18:17:49.154747

Next, datetime.now() function returns the current date and time. We can extract time through strftime() function.

# extract time from the date & time
currentTime = currentDay.strftime("%H:%M:%S")
print("Time;", currentTime)
# Output: Time: 18:26:57

We passed an argument containing three directives in strftime() function that converts date into the hours, minutes, and seconds. Following are the directives with their meanings,

  • %H: returns Hour 00 to 23
  • %M: returns Minute 00 to 59
  • %S: returns Second 00 to 59