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.
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
Import datetime from the datetime module.
- 2
Call datetime.now() to get a datetime object representing the current local time.
- 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.
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)Date Object: 2026-05-25
Year: 2026
Month: 5
Day: 25
Formatted Date: Monday, May 25, 2026Frequently 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.
Python Datetime
Learn how to handle dates, times, timezones, and calculations in Python. Master formatting, parsing, and arithmetic using datetime and timedelta.
Python DateTime Formatting
Learn how to parse and format dates and times in Python using datetime, strftime, and strptime.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.