Get the current date and time in Python

Read local or UTC time with datetime, obtain Unix timestamps, and use an elapsed-time clock when measuring how long code runs.

Best practices
Python programming and application logging

Use datetime.now() for the current local date and time, or datetime.now(timezone.utc) for a timezone-aware UTC value. Use time.time() when you need a Unix timestamp in seconds.

Format local time

from datetime import datetime

now = datetime.now()
print(now)
print(now.strftime("%H:%M:%S"))
print(now.strftime("%Y-%m-%d %H:%M:%S"))

The output depends on when and where the process runs. %Y, %m, and %d represent the year, month, and day; %H, %M, and %S represent the 24-hour clock time. A value returned without a timezone argument is naive: it does not store an explicit UTC offset.

Read a timestamp or use the time module

import time

print(time.strftime("%H:%M:%S", time.localtime()))
print(time.time())  # Seconds since the Unix epoch

A Unix timestamp represents an instant independently of the timezone used to display it. System clock adjustments can affect successive time.time() readings. Use time.perf_counter() for elapsed durations rather than subtracting wall-clock timestamps.

Keep timezone information

from datetime import datetime, timezone

now_utc = datetime.now(timezone.utc)
print(now_utc.isoformat())
print(now_utc.astimezone().isoformat())  # Local display with an offset

Storing an aware UTC value or a documented Unix timestamp makes cross-system comparisons less ambiguous. For a named regional timezone, use zoneinfo.ZoneInfo; its timezone database accounts for regional offset changes when data is available.

FAQ

How does today() differ? datetime.today() returns the current naive local time. datetime.now(tz) additionally accepts a timezone, which makes it more flexible.

How do I get milliseconds or microseconds? now.microsecond is the fractional microsecond component within one second. For an integer epoch value in milliseconds, use time.time_ns() // 1_000_000 on Python 3.7+. Nanosecond units do not imply nanosecond clock accuracy.

Which format should logs use? An ISO 8601 timestamp with an offset or an explicitly documented epoch unit is a useful choice. Configure and test the collector's timestamp parser; a logging platform should not be assumed to recognize every representation automatically.

References

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting