How do I get the current time in Python?

23    Asked by DeepakMistry in Python , Asked on May 20, 2025

What are the easiest ways to retrieve the current time in Python, and how do different modules like datetime or time handle it? This guide helps you understand how to display or manipulate the current time efficiently in your Python code.

Answered by FreemanHarris

To get the current time in Python, you can use built-in modules like datetime or time, depending on what format or precision you need. The most commonly used method is through the datetime module, which is part of Python’s standard library.

Here’s a simple and effective way using the datetime module:

from datetime import datetime
now = datetime.now()
print("Current Time:", now.strftime("%H:%M:%S"))

This will give you the current time formatted in hours, minutes, and seconds.

Alternatively, if you're interested in a timestamp (i.e., seconds since epoch), you can use the time module:

import time
current_time = time.time()
print("Current Timestamp:", current_time)

Other helpful tips:

  • Use .strftime() to format the time to your liking (e.g., 12-hour vs 24-hour).
  • If you only want the current hour or minute, you can access them like now.hour, now.minute, and now.second.
  • For timezone-aware time, consider using the pytz library or Python 3.9+'s zoneinfo.

Summary:

  • Use datetime.now() for readable time.
  • Use time.time() for timestamps.
  • Format output using .strftime().



Your Answer

Interviews

Parent Categories