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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github