DEV Community

Cover image for Python Get Current Timestamp
Mateen Kiani
Mateen Kiani

Posted on • Originally published at milddev.com

Python Get Current Timestamp

Introduction

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.

Using time module

The simplest way to grab a timestamp is with the time module:

import time

epoch_seconds = time.time()
print(f"Epoch seconds: {epoch_seconds}")
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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.
  • Both are naive (no timezone) and always in UTC.

Tip: Use time.time() for quick scripts; switch to datetime for more control.

Using datetime module

The datetime module offers a more object-oriented approach:

from datetime import datetime

# Local time
now = datetime.now()
print("Local now:", now)

# UTC time
utc_now = datetime.utcnow()
print("UTC now:", utc_now)

# As timestamp
ts = now.timestamp()
print("Epoch float:", ts)
Enter fullscreen mode Exit fullscreen mode

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.

Formatting timestamps

Raw epoch numbers aren’t human-friendly. Use strftime() or isoformat():

from datetime import datetime

t = datetime.now()
print(t.strftime("%Y-%m-%d %H:%M:%S"))   # 2023-08-15 14:55:02
print(t.isoformat())                       # 2023-08-15T14:55:02.123456
Enter fullscreen mode Exit fullscreen mode

Common directives:

  • %Y-%m-%d: Year-month-day
  • %H:%M:%S: Hour:Minute:Second
  • %f: Microseconds

Bullet points:

  • Use isoformat() for APIs and JSON.
  • Use strftime() for custom logs.
  • Avoid locale-specific formats unless needed.

Working with timezones

Managing timezones is crucial in global apps. Starting Python 3.9, use the built-in zoneinfo:

from datetime import datetime
from zoneinfo import ZoneInfo

# New York time
ny = datetime.now(tz=ZoneInfo("America/New_York"))
print("NY time:", ny)

# UTC time
utc = datetime.now(tz=ZoneInfo("UTC"))
print("UTC time:", utc)
Enter fullscreen mode Exit fullscreen mode

Before 3.9, many used pytz:

pip install pytz
Enter fullscreen mode Exit fullscreen mode
import pytz
from datetime import datetime

e = datetime.now(pytz.timezone("Europe/London"))
Enter fullscreen mode Exit fullscreen mode

Quote: “Timestamps without timezones are like letters without addresses.”

Epoch conversions

Often you need to switch between human dates and epoch:

from datetime import datetime

epoch = 1597762800
# Local datetime
dt_local = datetime.fromtimestamp(epoch)
# UTC datetime
dt_utc = datetime.utcfromtimestamp(epoch)

print(dt_local, dt_utc)
Enter fullscreen mode Exit fullscreen mode

Use these for:

  • Reading logs stored as epoch.
  • Scheduling tasks at specific epochs.
  • Debugging time-offset issues.

Advanced options

For higher precision or richer APIs, consider alternatives:

  • time.perf_counter() and time.monotonic() for performance benchmarks.
  • Third-party libraries like Pendulum:
import pendulum

now = pendulum.now()
print(now.to_iso8601_string())
Enter fullscreen mode Exit fullscreen mode

These tools help you choose the right source of truth, whether for metrics, logs, or data exchange.

Conclusion

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.

Top comments (0)