0
0
PythonHow-ToBeginner · 3 min read

How to Get Current Time in Python: Simple Guide

Use the datetime module to get the current time in Python. Call datetime.datetime.now() to get the current date and time, then use .time() to extract just the time.
📐

Syntax

To get the current time, import the datetime module and use datetime.datetime.now(). This returns the current date and time. To get only the time part, use .time() on the result.

python
import datetime

current_datetime = datetime.datetime.now()
current_time = current_datetime.time()
💻

Example

This example shows how to print the current time in hours, minutes, seconds, and microseconds.

python
import datetime

now = datetime.datetime.now()
current_time = now.time()
print("Current time is:", current_time)
Output
Current time is: 14:23:45.123456
⚠️

Common Pitfalls

  • Using time.time() returns a timestamp (seconds since 1970), not a formatted time.
  • For just the current time, remember to call .time() on the datetime object.
  • Don't forget to import the datetime module before using it.
python
import time

# Wrong: This gives a timestamp, not formatted time
print(time.time())

# Right: Use datetime for readable current time
import datetime
print(datetime.datetime.now().time())
Output
1700000000.123456 14:23:45.123456
📊

Quick Reference

Here is a quick summary of useful functions to get current time in Python:

FunctionDescription
datetime.datetime.now()Returns current date and time as a datetime object
datetime.datetime.now().time()Returns current time only
time.time()Returns current time as a timestamp (float seconds since epoch)

Key Takeaways

Use datetime.datetime.now() to get current date and time.
Call .time() on the datetime object to get only the current time.
Avoid using time.time() if you want a readable time format.
Always import the datetime module before using it.