How to get the current time in Python
Discover multiple ways to get the current time in Python, plus tips, real-world examples, and how to debug common errors.

You often need the current time in Python for logs, timestamps, or scheduled events. Python's built-in modules offer simple and powerful ways to handle time-related operations with precision.
In this article, you'll explore techniques to get the current time. You will find practical tips, real-world applications, and advice to debug and select the right approach for your project.
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 your go-to for fetching the current local time. It returns a datetime object that conveniently packages the date and time, offering precision down to the microsecond.
One crucial detail to remember is that datetime.now() produces a "naive" object. This means it lacks explicit timezone information, which can lead to bugs when your application handles multiple timezones. It simply reflects your system's local time without that extra context.
Basic time methods
To move beyond naive objects, you can work with raw timestamps using time.time(), format them with strftime(), or add crucial timezone information.
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 returns the current time as a raw timestamp. This isn't a date or time object but a floating-point number representing the seconds passed since the epoch—a standard reference point, which is January 1, 1970, on most systems.
- This raw number is useful for calculations but isn't human-readable on its own.
- You can convert the timestamp into a formatted string using
time.ctime(), as shown in the example.
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
The strftime() method gives you precise control over how you format a datetime object into a string. You pass it a string containing format codes, which act as placeholders for different time and date components.
- Codes like
%H,%M, and%Spull the hour, minute, and second. - You can get full names for days and months with
%Aand%B.
This flexibility lets you create custom, human-readable timestamps for any application, from log files to user interfaces.
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
To handle timezones correctly, you need "aware" datetime objects. You can create one by passing a timezone object to datetime.now(). For instance, datetime.now(timezone.utc) returns the current time in UTC—a universal standard perfect for server-side logic.
- This aware object includes an offset like
+00:00, making it unambiguous across different systems. - It's a clear contrast to a naive object from a simple
datetime.now()call, which lacks this crucial context.
Advanced time techniques
Beyond the standard library, you'll find powerful tools like pytz for complex timezones, arrow for a friendlier API, and time.perf_counter() for 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
When you need to manage complex timezones, especially those with daylight saving time, the pytz library is the standard solution. It provides a robust database of world timezones that goes beyond the fixed offsets in Python's built-in library.
- The recommended approach is to first create a timezone-aware object in UTC using
datetime.now(pytz.UTC). - You can then accurately convert this universal time to any specific timezone, like 'America/New_York', by calling the
astimezone()method. This two-step process helps you avoid common bugs related to time shifts.
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 offers a more intuitive way to handle dates and times in Python. Unlike the standard library, an object created with arrow.now() is timezone-aware by default, which helps you sidestep common bugs related to timezones.
- You can easily convert between timezones using the simple
to()method, such asnow.to('UTC'). - It also provides a convenient
humanize()method to generate relative, human-readable strings like "just now" or "in 5 minutes," which is 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. Unlike time.time(), it doesn't represent the actual time of day. Instead, it provides a high-resolution clock value that's perfect for benchmarking performance.
- The value it returns is only meaningful when subtracted from a later call, giving you the elapsed time.
- It's the most precise way to time operations in Python because it uses the system's highest-resolution clock available.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the time-handling techniques we've explored, Replit Agent can turn them into production-ready tools. For example, you could:
- Build a world clock dashboard that displays the current time in multiple cities, using
pytzto manage complex timezone and daylight saving rules. - Create a custom timestamp generator that formats the current time for log files or data entries based on user-defined
strftime()patterns. - Deploy a performance analysis tool that benchmarks Python functions by measuring their execution speed with
time.perf_counter().
Describe your app idea, and Replit Agent can write the code, test it, and fix issues automatically, all from your browser.
Common errors and challenges
Navigating time in Python can be tricky, but you can avoid common errors by understanding a few key concepts.
- Forgetting that
datetimeobjects are immutable. A common mistake is trying to change a part of adatetimeobject after you've created it, like updating its hour or year. These objects are immutable, meaning they can't be altered. Instead of changing the object, you must create a new one using thereplace()method, which returns a new object with your specified changes. - Timezone confusion with
astimezone(). Theastimezone()method is for converting an already timezone-aware object to a different timezone. A frequent error is calling it on a naivedatetimeobject—one without timezone information. Doing so causes Python to use your system's local timezone for the conversion, which can produce unexpected results. Always make an object aware first, for example withreplace(tzinfo=...), before converting it. - Using an incorrect format in
strptime(). Thestrptime()function parses a string into adatetimeobject, but it requires an exact match between the string's structure and the format codes you provide. If there's any mismatch, even a different separator like a slash instead of a hyphen, Python will raise aValueError. Always ensure your format string perfectly mirrors the date string you're parsing.
Forgetting that datetime objects are immutable
You might be tempted to update a datetime object in place, for instance, by adding to its hour attribute. However, datetime objects are immutable, meaning they can't be changed after creation. The following code shows the AttributeError this common mistake causes.
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 AttributeError happens because the code tries to directly modify the hour attribute with the += operator. Since datetime objects can't be altered once created, this operation fails. See the correct way to handle this 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}")
The correct approach is to create a new datetime object instead of modifying the existing one. You can do this by using a timedelta object, which represents a duration. By adding a timedelta(hours=2) to your original time, you generate a completely new datetime object that is two hours in the future. This method respects the immutability of the original object and avoids the AttributeError. Keep this in mind whenever you need to perform time calculations.
Timezone confusion with astimezone()
The astimezone() method is only for converting an already aware datetime object. A frequent mistake is trying to use it on a naive object to make it aware, which doesn't work and can cause unexpected errors. The code below shows this common mistake.
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}")
This code triggers a ValueError because astimezone() has no starting timezone to convert from. The object returned by datetime.now() is naive, lacking this crucial context. The example below demonstrates the correct approach.
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}")
The correct approach is to first make your naive datetime object aware. Use the localize() method from your pytz timezone object to attach the initial timezone information. For example, local_tz.localize(local_time) creates an aware object. Only then can you use astimezone() to accurately convert it to another timezone, such as UTC. This two-step process is crucial for reliable timezone conversions and prevents unexpected errors when dealing with time-sensitive data.
Using incorrect format in strptime()
The strptime() function converts strings to datetime objects, but it’s strict. The format string must perfectly mirror the date string's structure, down to the separators. Any mismatch, like using the wrong separator, will raise 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 "%d/%m/%Y %H:%M:%S" does not match the structure of the date string. The function requires a perfect match. See the corrected approach 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 corrected code works because the format string "%Y-%m-%d %H:%M:%S" now perfectly matches the structure of the date string. The strptime() function is unforgiving, so every character, including separators like hyphens, must align. You'll often encounter this issue when parsing dates from external sources like log files or APIs, where formats can be inconsistent. Always double-check that your format string mirrors the input to prevent a ValueError.
Real-world applications
Now that you know how to sidestep common time-handling errors, you can apply these skills to real-world applications.
Calculating age from birthdate using datetime
Calculating someone's age is a straightforward task with datetime, where you subtract the birth year from the current year and then make a simple adjustment to account for whether their birthday has already happened this year.
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 snippet calculates a person's precise age. It starts by subtracting the birth year from the current year. The key is the final part of the expression, which handles cases where the birthday hasn't occurred yet this year.
- It compares tuples of the current month and day with the birth month and day.
- If today's date is earlier in the calendar year than the birthday, the expression
((today.month, today.day) < (birthdate.month, birthdate.day))isTrue. - Python treats
Trueas1in calculations, so it subtracts one year from the result, giving you the correct age.
Tracking execution time with time.perf_counter()
To benchmark your code's performance, you can capture the elapsed time with time.perf_counter() and then format it into a human-readable duration.
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 snippet demonstrates how to precisely measure and format a task's duration. It captures the time before and after an operation using time.perf_counter(). Subtracting the start time from the end time gives you the total elapsed seconds as a floating-point number.
- The key step is passing this float to a
timedeltaobject, which is specifically designed to represent a duration. - Converting that
timedeltaobject to a string withstr()automatically formats the duration into a readableHH:MM:SS.microsecondslayout, making it easy to interpret in logs or reports.
Get started with Replit
Turn your knowledge into a real tool. Ask Replit Agent to "build a timezone converter for major world cities" or "create a script that calculates age from a birthdate."
The agent writes the code, tests for errors, and deploys your app from a simple prompt. Start building with Replit and bring your project to life.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)