Mateen Kiani
Published on Sun Jul 27 2025·3 min read
Getting the current timestamp in Python is one of the first tasks developers tackle when logging events or measuring performance. While time.time()
or datetime.now()
are commonly used, there’s a nuance many overlook: timezone awareness. How can you ensure your timestamp is accurate and meaningful across different regions?
By using Python’s built-in datetime
and zoneinfo
modules or third-party libraries, you can produce consistent, timezone-aware timestamps. This not only helps prevent confusion in distributed systems but also makes debugging and data analysis much smoother.
The simplest way to grab a timestamp is with the time
module:
import timeepoch_seconds = time.time()print(f"Epoch seconds: {epoch_seconds}")
This returns the number of seconds since January 1, 1970 (the Unix epoch). If you need nanosecond precision in Python 3.7+, try:
ns = time.time_ns()print(f"Nanoseconds since epoch: {ns}")
Keep in mind:
time.time()
yields a float, which may lose precision over long runs.time_ns()
gives integer nanoseconds but can be overkill for simple logs.Tip: Use
time.time()
for quick scripts; switch todatetime
for more control.
The datetime
module offers a more object-oriented approach:
from datetime import datetime# Local timenow = datetime.now()print("Local now:", now)# UTC timeutc_now = datetime.utcnow()print("UTC now:", utc_now)# As timestampts = now.timestamp()print("Epoch float:", ts)
Key points:
datetime.now()
uses system local time.datetime.utcnow()
returns UTC but still naive (no tz info)..timestamp()
converts a datetime
to epoch seconds.Many interview problems ask about these conversions—see Python interview questions for more practice.
Raw epoch numbers aren’t human-friendly. Use strftime()
or isoformat()
:
from datetime import datetimet = datetime.now()print(t.strftime("%Y-%m-%d %H:%M:%S")) # 2023-08-15 14:55:02print(t.isoformat()) # 2023-08-15T14:55:02.123456
Common directives:
%Y-%m-%d
: Year-month-day%H:%M:%S
: Hour:Minute:Second%f
: MicrosecondsBullet points:
isoformat()
for APIs and JSON.strftime()
for custom logs.Managing timezones is crucial in global apps. Starting Python 3.9, use the built-in zoneinfo
:
from datetime import datetimefrom zoneinfo import ZoneInfo# New York timeny = datetime.now(tz=ZoneInfo("America/New_York"))print("NY time:", ny)# UTC timeutc = datetime.now(tz=ZoneInfo("UTC"))print("UTC time:", utc)
Before 3.9, many used pytz
:
pip install pytz
import pytzfrom datetime import datetimee = datetime.now(pytz.timezone("Europe/London"))
Quote: “Timestamps without timezones are like letters without addresses.”
Often you need to switch between human dates and epoch:
from datetime import datetimeepoch = 1597762800# Local datetimedt_local = datetime.fromtimestamp(epoch)# UTC datetimedt_utc = datetime.utcfromtimestamp(epoch)print(dt_local, dt_utc)
Use these for:
For higher precision or richer APIs, consider alternatives:
time.perf_counter()
and time.monotonic()
for performance benchmarks.import pendulumnow = pendulum.now()print(now.to_iso8601_string())
These tools help you choose the right source of truth, whether for metrics, logs, or data exchange.
Getting the current timestamp in Python scales from a simple time.time()
call to fully timezone-aware objects with datetime
and zoneinfo
. By choosing the right method, you ensure your logs and data stay consistent across systems. Remember to format timestamps for readability, handle timezone conversions carefully, and explore high-precision or third-party options when your project demands it. Armed with these techniques, you’ll avoid the common pitfalls of naive timestamps and write more robust code.