How to Get the Current Date and Time in Python

Learn how to get the current date and time in Python using the datetime module. Format dates to strings with strftime and handle timezones.

Try Code in Editor

Explanation

Dealing with dates and times is a standard requirement in web development, database record keeping, analytics tracking, and automated job scheduling. Python provides robust, built-in tools to handle temporal operations via the `datetime` module.

To get the current date and time, the standard approach is calling `datetime.datetime.now()`. If you only need the calendar date (excluding hours, minutes, and seconds), you can use `datetime.date.today()`. These return date/datetime objects that expose individual fields like year, month, day, and hour as integers.

To display dates to users or save them in custom database formats, you must format these objects into strings. The `.strftime()` method (string format time) allows you to convert date objects to string representations using format codes like `%Y` for year, `%m` for month, and `%d` for day.

Step-by-Step Implementation

  1. 1

    Import datetime from the datetime module.

  2. 2

    Call datetime.now() to get a datetime object representing the current local time.

  3. 3

    Use the .strftime() method with format codes like %Y-%m-%d to serialize the date into a readable string.

Code Example

This script demonstrates working with datetime objects, extracting components, and formatting output.

get_date.py
Try in Editor
from datetime import datetime

# 1. Representing date and time using datetime
fixed_time = datetime(2026, 5, 25, 15, 45, 30)
print("Date Object:", fixed_time.date())

# 2. Extracting components
print("Year:", fixed_time.year)
print("Month:", fixed_time.month)
print("Day:", fixed_time.day)

# 3. Format date to string using strftime
formatted = fixed_time.strftime("%A, %B %d, %Y")
print("Formatted Date:", formatted)
Terminal Output
Date Object: 2026-05-25
Year: 2026
Month: 5
Day: 25
Formatted Date: Monday, May 25, 2026

Frequently Asked Questions

How do I get the current date in UTC time?

You can import the timezone module and use datetime.now(timezone.utc) or datetime.utcnow() (deprecated in Python 3.12).

What do strftime format codes like %Y, %m, and %d stand for?

%Y is the 4-digit year, %m is the 2-digit month (01-12), and %d is the 2-digit day of the month (01-31).

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.