How to Get Current Date in Python: Simple Guide
To get the current date in Python, use the
datetime module and call datetime.date.today(). This returns the current date as a date object representing year, month, and day.Syntax
Use the datetime module's date.today() method to get the current date. It returns a date object with year, month, and day.
datetime.date.today(): Gets current local date.datetime: The module that contains date and time classes.
python
from datetime import date current_date = date.today()
Example
This example shows how to get and print the current date in Python.
python
from datetime import date current_date = date.today() print("Today's date is:", current_date)
Output
Today's date is: 2024-06-15
Common Pitfalls
Some common mistakes include:
- Using
datetime.now()which returns date and time, not just the date. - Forgetting to import
datefromdatetime. - Trying to print the date without converting it to string (though
printhandles this automatically).
python
from datetime import datetime # Wrong: datetime.now() returns date and time current_date_time = datetime.now() print("Current date and time:", current_date_time) # Right: use date.today() for date only from datetime import date current_date = date.today() print("Current date:", current_date)
Output
Current date and time: 2024-06-15 10:30:45.123456
Current date: 2024-06-15
Quick Reference
Summary of methods to get current date:
| Method | Description | Returns |
|---|---|---|
date.today() | Current local date | Date object (year-month-day) |
datetime.now() | Current local date and time | Datetime object (year-month-day hour:min:sec) |
datetime.utcnow() | Current UTC date and time | Datetime object in UTC |
Key Takeaways
Use
date.today() from the datetime module to get the current date only.Remember to import
date from datetime before using it.datetime.now() returns date and time, not just the date.The returned date object can be printed directly or formatted as needed.
For UTC date and time, use
datetime.utcnow().