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:12
Common format codes:
%H= hour (24-hour clock)%M= minute%S= second%Y= 4-digit year%m= month%d= day
Using the time module
import time
current_seconds = time.time()
print(current_seconds)
Example output:
1777905012.123456
This is a Unix timestamp: seconds since January 1, 1970 UTC.
Beginner-friendly example
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
print("Current time only:", now.strftime("%H:%M:%S"))
This is a good beginner approach because it is readable and easy to extend later.
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)- Prints the full
datetimevalue. - Example:
2026-05-04 14:30:12.345678
- Prints the full
-
print(formatted_time)- Prints only the formatted time string.
- Example:
14:30:12
You can think of it as a two-step process:
- first get the current date-time object
- then decide how you want to display or use it
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.
Timing quick operations
import time
start = time.time()
# do work here
end = time.time()
print("Elapsed seconds:", end - start)
Useful for simple performance measurement.
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.
5. Simple performance timing with time
import time
start = time.time()
for _ in range(100000):
pass
print(time.time() - start)
This is common in scripts and quick checks.
In larger codebases, choosing the right form early helps avoid confusion later.
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 now without parentheses
Broken code:
from datetime import datetime
now = datetime.now
print(now)
Problem:
- This stores the function itself, not the current time.
Correct code:
from datetime import datetime
now = datetime.now()
print(now)
4. Expecting a formatted string automatically
Broken assumption:
from datetime import datetime
now = datetime.now()
print("Time:", now)
This works, but it prints the default datetime format, not a custom one.
Use strftime() when you need a specific format:
print(now.strftime("%H:%M:%S"))
5. Using multiple now() calls when one is enough
from datetime import datetime
print(datetime.now().strftime("%H:%M:%S"))
print(datetime.now().strftime("%Y-%m-%d"))
Problem:
- The two values may differ slightly because they are fetched separately.
Better:
from datetime import datetime
now = datetime.now()
print(now.strftime("%H:%M:%S"))
print(now.strftime("%Y-%m-%d"))
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 | Calculations and simple timing | 1777905012.123 |
datetime vs time
| Feature | datetime module | time module |
|---|---|---|
| Easy to read | Yes | Less human-friendly |
| Good for formatting | Yes | Limited directly |
| Good for timestamps | Yes, with conversion | Yes |
| Good for elapsed seconds | Possible | Very common |
| Best beginner choice | Usually yes | Sometimes |
Which should you use?
- Use
datetime.now()when you want the current date/time in a structured way. - Use
strftime()when you want to display it nicely. - Use
time.time()when you need a numeric timestamp or want to measure duration quickly.
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
datetime.now()returns adatetimeobjectstrftime()returns a stringtime.time()returns a float- import correctly:
from datetime import datetime - call functions with parentheses:
datetime.now()notdatetime.now
Handy pattern
from datetime import datetime
now = datetime.now()
print(now)
print(now.strftime("%H:%M:%S"))
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 time.time() for simple timing or timestamp calculations.
Why does import datetime work differently from from datetime import datetime?
Because import datetime imports the module, while from datetime import datetime imports the datetime class directly.
That is why these differ:
import datetime
datetime.datetime.now()
from datetime import datetime
datetime.now()
Can I use the current time in filenames?
Yes. This is very common:
from datetime import datetime
filename = datetime.now().strftime("report_%Y%m%d_%H%M%S.txt")
Is datetime better than time for beginners?
Usually yes, because it is easier to read and format. The time module is still useful for timestamps and measuring durations.
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.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.