How do I get the current time in Python?

Better Stack Team
Updated on January 26, 2023

There are two ways you can get the current time in python.

  • using the datetime object
  • using the time module

Using the datetime object

First, you need to import the datetime module. Then by calling the now method, you can create a datetime object containing the current date and time.

 
from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print(current_time)

This will output:

 
11:26:11

Using the strftime you can convert the datetime to a string by specifying the format.

Using the time module

First, import the time module, then call the localtime method to create a time object.

 
import time

t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)
 
11:26:11

Using the strftime you can convert the time to a string by specifying the format.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →