Question

How to Get the Current Time in Python

pythondatetimetime

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:

  • datetime from the datetime module
  • functions from the time module

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 together
  • time.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 datetime and format it
Take Quiz

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:

  1. from datetime import datetime

    • Imports the datetime class from Python's datetime module.
  2. now = datetime.now()

    • Calls the now() method.
    • Python asks the system for the current local date and time.
    • The result is stored in now as a datetime object.
  3. formatted_time = now.strftime("%H:%M:%S")

    • Converts the datetime object into a string.
    • The format says: hour, minute, second.
    • Example result: 14:30:12
  4. print(now)

    • Prints the full datetime value.
    • Example: 2026-05-04 14:30:12.345678
  5. 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.

Take Quiz

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:

  • datetime is 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:

  • datetime here 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

ApproachWhat it returnsBest forExample
datetime.now()A datetime objectMost date/time workdatetime.now()
datetime.now().time()A time objectTime onlydatetime.now().time()
datetime.now().strftime(...)A formatted stringDisplaying time"14:30:12"
time.time()Unix timestamp as floatCalculations and simple timing1777905012.123

datetime vs time

Featuredatetime moduletime module
Easy to readYesLess human-friendly
Good for formattingYesLimited directly
Good for timestampsYes, with conversionYes
Good for elapsed secondsPossibleVery common
Best beginner choiceUsually yesSometimes

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.
Take Quiz

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

  • %H hour (00-23)
  • %M minute (00-59)
  • %S second (00-59)
  • %Y year
  • %m month
  • %d day

Common rules

  • datetime.now() returns a datetime object
  • strftime() returns a string
  • time.time() returns a float
  • import correctly: from datetime import datetime
  • call functions with parentheses: datetime.now() not datetime.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 object
  • time.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.

Take Quiz

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." ]

Take Quiz

Keep learning

Related questions

View more