Question
How can I get the current time in Python?
I want to retrieve the current time from my Python program and understand the usual ways to do it correctly.
Short Answer
By the end of this page, you will understand how to get the current time in Python, when to use the datetime module versus the time module, how to format the result, and what common mistakes beginners should avoid.
Concept
In Python, getting the current time usually means asking the operating system for the current date and time, then working with that value in your program.
The most common tools are:
datetimefrom thedatetimemodule- functions from the
timemodule
For most applications, datetime is the preferred choice because it gives you a structured object with useful parts like:
- year
- month
- day
- hour
- minute
- second
Example:
from datetime import datetime
now = datetime.now()
print(now)
This returns a datetime object representing the current local date and time.
Why this matters in real programming:
- logging events with timestamps
- showing current time in apps
- measuring when something happened
- generating filenames with timestamps
- comparing times and dates
If you only need a raw timestamp or lower-level time functions, the time module is also useful.
import time
current_timestamp = time.time()
print(current_timestamp)
That returns the number of seconds since the Unix epoch, which is useful for storage, calculations, and timing operations.
Mental Model
Think of Python's time tools like different kinds of clocks:
datetime.now()is like looking at a wall clock and calendar togethertime.time()is like reading a stopwatch number used by computers- formatted time strings are like writing the clock reading neatly on paper
So the question is not only "What time is it?" but also "In what form do I need the answer?"
- Human-readable date and time? Use
datetime - Numeric timestamp for calculations? Use
time.time() - Just a formatted string? Get a
datetimeand format it
Syntax and Examples
Using datetime.now()
from datetime import datetime
now = datetime.now()
print(now)
This prints the current local date and time, for example:
2026-05-04 14:30:12.345678
Getting only the current time part
from datetime import datetime
current_time = datetime.now().time()
print(current_time)
Example output:
14:30:12.345678
Formatting the current time
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%H:%M:%S")
print(formatted)
Output:
14:30:
Step by Step Execution
Consider this code:
from datetime import datetime
now = datetime.now()
formatted_time = now.strftime("%H:%M:%S")
print(now)
print(formatted_time)
Step by step:
-
from datetime import datetime- Imports the
datetimeclass from Python'sdatetimemodule.
- Imports the
-
now = datetime.now()- Calls the
now()method. - Python asks the system for the current local date and time.
- The result is stored in
nowas adatetimeobject.
- Calls the
-
formatted_time = now.strftime("%H:%M:%S")- Converts the
datetimeobject into a string. - The format says: hour, minute, second.
- Example result:
14:30:12
- Converts the
-
print(now)
Real World Use Cases
Here are common situations where getting the current time is useful:
Logging
from datetime import datetime
print(f"[{datetime.now()}] Application started")
Used in scripts, servers, and debugging.
Timestamps for filenames
from datetime import datetime
filename = f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
print(filename)
Useful for backups, reports, and exported data.
Showing the current time in an app
from datetime import datetime
current_time = datetime.now().strftime("%H:%M:%S")
print("Current time:", current_time)
Common in dashboards, tools, and command-line programs.
Measuring when an event happened
from datetime import datetime
created_at = datetime.now()
print(created_at)
Often stored for records, logs, or audit trails.
Real Codebase Usage
In real projects, developers usually choose the time representation based on what the code needs.
Common patterns
1. Capture once, reuse many times
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d"))
print(now.strftime("%H:%M:%S"))
This avoids calling datetime.now() multiple times and accidentally getting slightly different values.
2. Store timestamps in a consistent format
from datetime import datetime
created_at = datetime.now().isoformat()
print(created_at)
isoformat() is common in APIs, databases, and logs.
3. Use current time in validation or comparisons
from datetime import datetime, timedelta
expires_at = datetime.now() + timedelta(minutes=30)
print(expires_at)
Common for sessions, tokens, bookings, and deadlines.
4. Early formatting at the display layer
Developers often keep values as datetime objects in the program logic, then format them only when displaying or exporting them.
Common Mistakes
1. Forgetting to import the right module
Broken code:
now = datetime.now()
print(now)
Problem:
datetimeis not defined unless you import it.
Correct code:
from datetime import datetime
now = datetime.now()
print(now)
2. Confusing the module name with the class name
Broken code:
import datetime
now = datetime.now()
print(now)
Problem:
datetimehere refers to the module, not the class.
Correct code:
import datetime
now = datetime.datetime.now()
print(now)
Or:
from datetime import datetime
now = datetime.now()
print(now)
3. Calling without parentheses
Comparisons
| Approach | What it returns | Best for | Example |
|---|---|---|---|
datetime.now() | A datetime object | Most date/time work | datetime.now() |
datetime.now().time() | A time object | Time only | datetime.now().time() |
datetime.now().strftime(...) | A formatted string | Displaying time | "14:30:12" |
time.time() | Unix timestamp as float |
Cheat Sheet
from datetime import datetime
import time
Get current local date and time
now = datetime.now()
Get current time only
current_time = datetime.now().time()
Format as string
datetime.now().strftime("%H:%M:%S")
datetime.now().strftime("%Y-%m-%d")
datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Get Unix timestamp
time.time()
Common format codes
%Hhour (00-23)%Mminute (00-59)%Ssecond (00-59)%Yyear%mmonth%dday
Common rules
- returns a object
FAQ
How do I get the current time only in Python?
Use:
from datetime import datetime
print(datetime.now().time())
If you want a cleaner display, format it with strftime().
What is the easiest way to get the current time in Python?
For most beginners, this is the easiest:
from datetime import datetime
print(datetime.now())
How do I format the current time as HH:MM:SS?
Use:
from datetime import datetime
print(datetime.now().strftime("%H:%M:%S"))
What is the difference between datetime.now() and time.time()?
datetime.now()gives a structured date-time objecttime.time()gives a numeric Unix timestamp
Use datetime.now() for readable date/time work and for simple timing or timestamp calculations.
Mini Project
Description
Build a small Python script that prints the current time in multiple formats and creates a timestamped filename. This demonstrates how to retrieve the current time once, reuse it, and format it for different purposes.
Goal
Create a script that gets the current time, displays it in readable formats, and generates a filename using a timestamp.
Requirements
[ "Get the current date and time using Python.", "Print the full current date and time.", "Print the time in HH:MM:SS format.", "Create and print a filename that includes the current timestamp." ]
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.