Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Get Current Date Time Python: 6 Ways

· 4 min read · Home Tech

In this article
  1. Why the datetime Module Is the Standard
  2. Getting the Current Local Date and Time
  3. Getting UTC (Coordinated Universal Time)
  4. Formatting the Date and Time for Display
  5. Working with Timezones
  6. Common Mistakes and Pitfalls
  7. Alternatives: time Module and Third-Party Libraries
  8. Frequently Asked Questions

To get the current date and time in Python, use the built-in datetime module: from datetime import datetime; now = datetime.now(). This returns a datetime object containing the current local date and time, which you can then format or extract components from.

Why the datetime Module Is the Standard

Python's datetime module is part of the standard library, meaning it ships with every Python installation. It provides the datetime class, which represents a specific moment in time as a combination of year, month, day, hour, minute, second, and microsecond. The module also includes date, time, and timedelta classes for working with dates and times separately or performing arithmetic. Because it's built-in, there's no need to install anything extra, and it's the most widely used approach for handling dates and times in Python.

Getting the Current Local Date and Time

The most common way to get the current date and time is using datetime.now(). This returns the local date and time based on your system's timezone settings. Here's a simple example:

from datetime import datetime

now = datetime.now()
print(now)  # Output: 2025-03-21 14:35:22.123456

If you only need the current date or the current time separately, you can use date.today() or datetime.now().time() respectively:

from datetime import date, datetime

today = date.today()
current_time = datetime.now().time()
print(today)        # 2025-03-21
print(current_time) # 14:35:22.123456

Getting UTC (Coordinated Universal Time)

When you need a timezone-independent timestamp (for logging, APIs, or databases), use datetime.utcnow() to get the current UTC time. However, note that utcnow() returns a naive datetime (no timezone info). For a timezone-aware UTC datetime, use datetime.now(timezone.utc):

from datetime import datetime, timezone

utc_now = datetime.now(timezone.utc)
print(utc_now)  # 2025-03-21 14:35:22.123456+00:00

The timezone.utc argument attaches the UTC timezone, making it aware. This is recommended for any operation that involves timezone conversions or comparisons.

Formatting the Date and Time for Display

To turn a datetime object into a human-readable string, use the strftime() method (string format time). It accepts a format string with directives like %Y for year, %m for month, %d for day, %H for hour (24-hour), %I for hour (12-hour), %M for minute, %S for second, and %p for AM/PM. Here are common examples:

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # 2025-03-21 14:35:22
print(now.strftime("%d/%m/%Y"))            # 21/03/2025
print(now.strftime("%I:%M %p"))            # 02:35 PM

You can also use isoformat() to get an ISO 8601 string (e.g., 2025-03-21T14:35:22.123456), which is useful for data interchange.

Working with Timezones

For applications that deal with users in different timezones, you'll need timezone-aware datetimes. The zoneinfo module (available since Python 3.9) provides access to the IANA timezone database. You can create a timezone-aware datetime and convert between timezones:

from datetime import datetime
from zoneinfo import ZoneInfo

now_utc = datetime.now(ZoneInfo("UTC"))
now_newyork = now_utc.astimezone(ZoneInfo("America/New_York"))
print(now_newyork)  # 2025-03-21 10:35:22.123456-04:00

If you need to support older Python versions (before 3.9), the third-party pytz library is a common alternative, but zoneinfo is now the recommended standard.

Common Mistakes and Pitfalls

  • Using datetime.now() vs datetime.utcnow(): Mixing naive local and naive UTC datetimes can lead to errors. Always be explicit about which one you're using.
  • Forgetting to import: from datetime import datetime is required; many beginners mistakenly use import datetime and then try datetime.datetime.now().
  • Formatting errors: Using %Y (four-digit year) vs %y (two-digit year) can produce unexpected results. Double-check your format string.
  • Timezone-naive arithmetic: Subtracting two naive datetimes can be ambiguous if they were created in different timezones. Always use aware datetimes when doing arithmetic across timezones.

Alternatives: time Module and Third-Party Libraries

Besides datetime, Python's time module can give you the current Unix timestamp (seconds since epoch) with time.time(). This is useful for measuring elapsed time or working with timestamps in APIs. For more advanced date handling, libraries like dateutil (for parsing and relative deltas) and pendulum (for a more intuitive API) exist, but they are not part of the standard library and require installation. For most use cases, the built-in datetime module is sufficient and recommended.

Frequently Asked Questions

How do I get the current date and time as a string?

Use datetime.now().strftime("%Y-%m-%d %H:%M:%S") to get a formatted string. You can customize the format to your preference.

What is the difference between datetime.now() and datetime.utcnow()?

datetime.now() returns the local date and time, while datetime.utcnow() returns the UTC date and time. Both are naive (no timezone info). For aware datetimes, use datetime.now(timezone.utc).

How do I get the current timestamp in Unix format?

Use time.time() to get the current Unix timestamp as a float. Alternatively, datetime.now().timestamp() gives the same for a datetime object.

How do I convert a datetime object to a string in ISO format?

Call isoformat() on the datetime object, e.g., datetime.now().isoformat() returns 2025-03-21T14:35:22.123456.

How do I get the current time in a specific timezone?

Use datetime.now(ZoneInfo("America/New_York")) with the zoneinfo module. Replace the timezone name with any valid IANA timezone.