How to get the current time in Python

Learn how to get the current time in Python. Explore various methods, tips, real-world uses, and common error debugging.

How to get the current time in Python
Published on: 
Thu
Feb 12, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

You often need the current time in Python for logs, timestamps, and scheduled tasks. Python's standard libraries, like datetime, offer simple tools to handle time-related operations with precision and ease.

In this article, we'll explore several techniques to get the current time, along with practical tips for implementation. We also cover real-world applications and debugging advice to help you confidently manage time in your projects.

Using datetime.now() for current time

from datetime import datetime
current_time = datetime.now()
print(current_time)--OUTPUT--2023-08-20 14:30:45

The datetime.now() function is the most straightforward way to capture the current local time. It returns a special datetime object, which is more than just a timestamp. It’s a data structure that holds detailed information about the current moment.

This object contains individual attributes for the year, month, day, hour, minute, second, and even microsecond. When you print it, you get a default string representation like 2023-08-20 14:30:45. The real advantage, however, is that you can access each part of the date and time separately for calculations or custom formatting.

Basic time methods

While datetime.now() is great for a quick snapshot, you'll often need more control for formatting, handling timestamps, or working across timezones.

Using time.time() to get timestamp

import time
timestamp = time.time()
print(f"Current timestamp: {timestamp}")
print(f"Formatted time: {time.ctime(timestamp)}")--OUTPUT--Current timestamp: 1692546789.123456
Formatted time: Sun Aug 20 14:30:45 2023

The time.time() function gives you the current time as a Unix timestamp. This is a floating-point number representing the seconds that have passed since January 1, 1970. Timestamps are great for arithmetic and for storing time data compactly. Learn more about getting timestamp in Python with various methods.

  • While useful, a raw timestamp like 1692546789.123456 isn't easy for humans to read.
  • You can convert it into a more familiar format using time.ctime(), which returns a readable string like Sun Aug 20 14:30:45 2023.

Formatting time with strftime()

from datetime import datetime
now = datetime.now()
formatted_time = now.strftime("%H:%M:%S on %A, %B %d, %Y")
print(formatted_time)--OUTPUT--14:30:45 on Sunday, August 20, 2023

For complete control over your time output, the strftime() method is your best tool. It lets you format a datetime object into a custom string using special codes. Think of these codes as placeholders for different time components.

  • %H, %M, and %S stand for the hour, minute, and second.
  • %A and %B represent the full weekday and month names.
  • %d is the day of the month, and %Y is the four-digit year.

By combining these codes, you can build any time format you need. This flexibility is essential when changing date format in Python for different display requirements.

Working with timezone-aware times

from datetime import datetime, timezone
utc_time = datetime.now(timezone.utc)
print(f"UTC time: {utc_time}")
local_time = datetime.now()
print(f"Local time: {local_time}")--OUTPUT--UTC time: 2023-08-20 18:30:45.123456+00:00
Local time: 2023-08-20 14:30:45.123456

When your application handles time across different regions, it's crucial to manage timezones correctly. Python's datetime objects can be either "naive" or "aware."

  • A naive object, returned by a simple datetime.now() call, has no timezone information.
  • An aware object is created by passing a timezone, like with datetime.now(timezone.utc). This attaches timezone data, making your timestamps unambiguous. Using UTC is a common best practice for backend systems to ensure consistency.

Advanced time techniques

For more advanced needs, libraries like pytz and arrow simplify timezone handling, while functions like time.perf_counter() offer high-precision timing.

Using the pytz library for timezone handling

from datetime import datetime
import pytz
utc_time = datetime.now(pytz.UTC)
ny_time = utc_time.astimezone(pytz.timezone('America/New_York'))
print(f"New York time: {ny_time}")--OUTPUT--New York time: 2023-08-20 10:30:45.123456-04:00

While Python's standard library handles basic timezone tasks, the pytz library offers more robust control for complex conversions. It's the go-to solution when you need to work with specific geographical timezones, not just UTC.

  • After creating an aware UTC time object, you can use the astimezone() method to convert it.
  • Passing a pytz.timezone() object—like 'America/New_York'—accurately shifts the time, automatically accounting for complexities like Daylight Saving Time.

Simplified time handling with arrow

import arrow
now = arrow.now()
print(f"Current time: {now}")
print(f"UTC time: {now.to('UTC')}")
print(f"Humanized: {now.humanize()}")--OUTPUT--Current time: 2023-08-20T14:30:45.123456-04:00
UTC time: 2023-08-20T18:30:45.123456+00:00
Humanized: just now

The arrow library is a popular alternative that simplifies date and time manipulation in Python. It provides a more sensible and human-friendly approach, wrapping the power of other libraries into a cleaner API. For instance, arrow.now() automatically creates a timezone-aware object, which is a common source of bugs when forgotten.

  • Converting timezones is straightforward with the .to() method, such as now.to('UTC').
  • It also offers a unique .humanize() method that creates relative time strings like "just now," perfect for user interfaces.

High precision timing with time.perf_counter()

import time
start = time.perf_counter()
# Simulating some operation
time.sleep(0.1)
end = time.perf_counter()
print(f"Operation took {end - start:.6f} seconds")--OUTPUT--Operation took 0.100123 seconds

When you need to measure how long a piece of code takes to run, time.perf_counter() is the right tool for the job. It provides a high-precision clock value that's ideal for measuring performance. Unlike time.time(), its value always moves forward and isn't affected by system time updates, ensuring your measurements are accurate.

  • You capture a starting value before your code runs.
  • Then you capture an ending value right after.
  • The difference between these two values gives you the precise execution time in seconds.

Move faster with Replit

Replit is an AI-powered development platform where all Python dependencies are pre-installed, so you can skip setup and start coding instantly. This allows you to move from learning individual techniques to building complete applications faster. With Agent 4, you can describe an idea, and it will handle the code, APIs, and deployment.

Instead of piecing together methods, you can build complete apps that use the time functions covered in this article, such as:

  • A world clock dashboard that converts a UTC timestamp to display the current time in several major cities.
  • A performance logger that uses time.perf_counter() to track and record how long different functions take to run.
  • A countdown utility that shows the time remaining until an event in a human-friendly format, like “in 3 hours.”

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Working with time in Python can be tricky; here are a few common pitfalls and how you can avoid them.

Forgetting that datetime objects are immutable

A frequent mistake is trying to change a part of a datetime object after it has been created. These objects are immutable, which means their values can't be altered. Attempting to directly modify an attribute like my_time.year = 2024 will result in an error. Instead, you should use the replace() method. This function returns a new datetime object with your specified changes, leaving the original one intact.

Timezone confusion with astimezone()

Calling astimezone() on a naive datetime object—one without any timezone information—is a classic stumbling block. Python can't convert a time if it doesn't know the starting timezone, so it raises a ValueError. To fix this, you must first make the object "aware" by attaching a timezone with replace(tzinfo=...) before you can correctly convert it with astimezone().

Using incorrect format in strptime()

The strptime() function, which parses a string into a datetime object, requires the format code to be an exact match. If the format string you provide doesn't perfectly align with the input string, Python will raise a ValueError. You need to ensure every character, from slashes to spaces, in your format string corresponds precisely to the date string you're trying to parse.

Forgetting that datetime objects are immutable

A common reflex is to modify an object’s attributes directly, but datetime objects are immutable—their values can't be changed after creation. Attempting to adjust the hour with an operator like += will cause an error. The following code demonstrates this pitfall.

from datetime import datetime
meeting_time = datetime.now()
print(f"Original meeting time: {meeting_time}")
meeting_time.hour += 2 # This will raise an AttributeError
print(f"Updated meeting time: {meeting_time}")

The code triggers an AttributeError because the += operator attempts to change the hour attribute directly. This fails since datetime objects are immutable and don't support in-place changes. Check out the correct implementation below.

from datetime import datetime, timedelta
meeting_time = datetime.now()
print(f"Original meeting time: {meeting_time}")
updated_meeting = meeting_time + timedelta(hours=2)
print(f"Updated meeting time: {updated_meeting}")

To correctly modify a datetime object, you must create a new one. The solution uses a timedelta object, which represents a duration, and adds it to the original time. This operation returns a new object with the adjusted value, leaving the original unchanged. You'll find this technique essential for any time-based arithmetic, such as calculating future appointments or expiration dates, especially when building scheduling or logging features.

Timezone confusion with astimezone()

Applying astimezone() to a naive datetime object is a frequent misstep. Since the object has no timezone information, Python can't perform the conversion and raises a ValueError. The code below shows exactly how this common error occurs.

from datetime import datetime
import pytz

local_time = datetime.now()
utc_time = local_time.astimezone(pytz.UTC) # ValueError: naive datetime
print(f"UTC time: {utc_time}")

The code fails because datetime.now() returns a naive object. The astimezone() method can't convert a time without knowing its starting timezone. The following example shows the correct way to handle this conversion.

from datetime import datetime
import pytz

local_time = datetime.now()
local_tz = pytz.timezone('America/New_York')
aware_time = local_tz.localize(local_time)
utc_time = aware_time.astimezone(pytz.UTC)
print(f"UTC time: {utc_time}")

To solve this, you'll first need to make the naive object "aware." The pytz library's localize() method handles this by attaching a starting timezone. Once the object knows its origin, you can safely call astimezone() to convert it to another timezone, like UTC. This is essential for apps that manage data across different regions, as it ensures all your timestamps are standardized and reliable.

Using incorrect format in strptime()

The strptime() function is strict. It requires the format string to perfectly mirror the date string you're parsing. If there's any mismatch, like a dash where a slash is expected, Python raises a ValueError. See this common error in action below.

from datetime import datetime

log_date = "2023-08-20 14:30:45"
parsed_date = datetime.strptime(log_date, "%d/%m/%Y %H:%M:%S") # Wrong format
print(f"Parsed date: {parsed_date}")

This code raises a ValueError because the format string specifies slashes (/) as separators, but the actual date string uses dashes (-). See how to fix this mismatch in the example below.

from datetime import datetime

log_date = "2023-08-20 14:30:45"
parsed_date = datetime.strptime(log_date, "%Y-%m-%d %H:%M:%S") # Correct format
print(f"Parsed date: {parsed_date}")

The solution is to make the format string in strptime() an exact match for the date string. By changing the format to "%Y-%m-%d %H:%M:%S", the code now correctly mirrors the input's structure, including the dashes. You'll need to be careful with this when parsing dates from external sources like log files or APIs, as their formats can often be inconsistent and cause unexpected errors if not handled precisely. Understanding converting datetime to string helps with the reverse operation.

Real-world applications

Knowing how to avoid common errors lets you confidently use these time functions to solve real-world problems.

A classic example is calculating someone's age. You can do this by taking the current date from datetime.now() and subtracting a person's birthdate. The result is a timedelta object, which represents the exact duration between the two dates. To get the age in years, you can simply divide the .days attribute by 365.25 to account for leap years. For more detailed methods on calculating age in Python, explore different approaches.

Another practical use is performance monitoring. By using time.perf_counter(), you can precisely measure how long specific parts of your code take to run. This is invaluable for optimizing your application's speed by identifying bottlenecks or comparing the efficiency of different algorithms, especially when using vibe coding to rapidly prototype solutions.

Calculating age from birthdate using datetime

You can precisely calculate age by subtracting the birth year from the current year and using a simple tuple comparison to adjust for whether the birthday has already passed.

from datetime import datetime

birthdate = datetime(1990, 5, 15)
today = datetime.now()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
print(f"Age: {age} years")

This approach first calculates the simple difference between the current year and the birth year. The real magic, however, happens in the final part of the calculation.

  • The expression (today.month, today.day) < (birthdate.month, birthdate.day) compares the month and day tuples.
  • This check returns True, which Python treats as the integer 1, if the birthday hasn't occurred yet this year. Otherwise, it returns False, or 0.

Subtracting this boolean result from the year difference provides an accurate age without needing a more complex if-else block.

Tracking execution time with time.perf_counter()

You can make these performance measurements easier to read by using timedelta to convert the raw seconds from time.perf_counter() into a standard time format.

import time
from datetime import timedelta

start = time.perf_counter()
# Simulate a long-running operation
time.sleep(2.5)
end = time.perf_counter()

elapsed = end - start
formatted_time = str(timedelta(seconds=elapsed))
print(f"Operation took {formatted_time}")

This code shows how to present performance measurements in a more structured format. After calculating the raw `elapsed` time in seconds with time.perf_counter(), the value is used to create a timedelta object.

  • A timedelta object represents a duration—a span of time—rather than a specific moment.
  • Converting this object to a string automatically formats the duration into a clean H:MM:SS.ffffff layout.

This technique is great for logging or displaying performance data where a simple float isn't descriptive enough, particularly useful when building applications through AI coding with Python.

Get started with Replit

Turn your knowledge into a working tool. Describe what you want to build to Replit Agent, like “a world clock dashboard for three timezones” or “a countdown utility that shows time until an event.”

Replit Agent will write the code, test for errors, and deploy your application for you. Start building with Replit and see your project come together in minutes.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.