How to get today's date in Python
Learn how to get today's date in Python. You'll find different methods, real-world applications, and tips for debugging common errors.
You often need the current date in Python for logging, timestamping, or scheduling tasks. The datetime module provides simple and powerful tools to handle this common requirement.
In this article, we'll cover various techniques to get today's date. You'll find practical tips, see real-world applications, and get advice for debugging common issues.
Getting today's date with datetime
from datetime import datetime
today = datetime.now()
print(today)--OUTPUT--2023-10-24 15:30:45
The datetime.now() method is the most direct way to capture the current moment. It creates a datetime object containing both the current local date and time, which is why the output includes the time down to the microsecond.
This combined object is perfect for precise timestamping. However, if you only need the date, you'll have to extract it. The object returned by datetime.now() conveniently stores date and time components separately, making this a straightforward task. For more specific techniques on getting timestamps in Python, including Unix timestamps and different formats.
Common date formats
For situations where you only need the date, or need to present it in a specific way, Python offers cleaner methods like date.today() and strftime().
Using date.today() for date without time
from datetime import date
today_date = date.today()
print(today_date)--OUTPUT--2023-10-24
When you only need the current date, date.today() is the most straightforward approach. It returns a date object that exclusively contains year, month, and day information, which is perfect for date-centric logic.
- It’s more direct than extracting the date from a
datetime.now()object. - The resulting
dateobject is simpler to work with when time isn't relevant. - It helps keep your code focused and readable.
Formatting dates with strftime()
from datetime import datetime
today = datetime.now()
formatted_date = today.strftime("%Y-%m-%d")
print(formatted_date)--OUTPUT--2023-10-24
When you need full control over how a date appears, the strftime() method is your go-to tool. It converts a datetime object into a string according to a format you define. The format string uses special codes to represent different parts of the date.
%Ystands for the full four-digit year.%mrepresents the month as a zero-padded number.%dis the day of the month as a zero-padded number.
This gives you the flexibility to create any date format you need for reports, filenames, or user interfaces.
Creating custom date formats
from datetime import datetime
today = datetime.now()
custom_format = today.strftime("%A, %B %d, %Y")
print(custom_format)--OUTPUT--Tuesday, October 24, 2023
The strftime() method isn't limited to just numerical dates. You can create more descriptive, human-readable formats by using different codes. This example produces a full date string like "Tuesday, October 24, 2023" by combining several format specifiers.
%Agives you the full weekday name.%Bprovides the full month name.%dand%Yrepresent the day and year, just as before.
This flexibility allows you to tailor date strings for any context, from log files to user-facing displays. For more comprehensive coverage of changing date formats in Python, including additional formatting options and techniques.
Advanced date techniques
Moving beyond simple formatting, you can handle more complex scenarios like performing date arithmetic with timedelta, working with timezones, and parsing dates with the dateutil library. For rapid prototyping of date-based applications, vibe coding can help you quickly build and iterate on your ideas.
Using timedelta for date calculations
from datetime import datetime, timedelta
today = datetime.now()
tomorrow = today + timedelta(days=1)
print(f"Tomorrow: {tomorrow.date()}")--OUTPUT--Tomorrow: 2023-10-25
The timedelta object is your tool for date calculations. It represents a duration, like a span of days or hours, which you can add to or subtract from a datetime object to find a new date. When working with large datasets or frequent date operations, consider memory efficiency to avoid potential performance issues.
- Here,
timedelta(days=1)creates a duration of one day. - Adding it to the current date effectively moves time forward to tomorrow.
- This same logic works for finding past dates or calculating with other units like
weeks,hours, andminutes.
Getting timezone-aware dates
from datetime import datetime
import pytz
utc_now = datetime.now(pytz.UTC)
est_now = utc_now.astimezone(pytz.timezone('US/Eastern'))
print(f"Eastern time: {est_now}")--OUTPUT--Eastern time: 2023-10-24 15:30:45.123456-04:00
When your application serves users across different regions, you'll need timezone-aware dates. The pytz library is the standard solution for this. Best practice is to get the current time in a universal standard like UTC using datetime.now(pytz.UTC).
- This gives you a reliable, timezone-aware starting point.
- You can then convert this UTC time to any local timezone with the
astimezone()method.
The example does exactly this, converting the UTC time to US Eastern Time to get an accurate, localized timestamp. For more techniques on getting current time in Python, including different time formats and timezone handling.
Using the dateutil library for parsing
from dateutil import parser
date_string = "Oct 24, 2023"
parsed_date = parser.parse(date_string)
print(parsed_date)--OUTPUT--2023-10-24 0:00:00
While Python's built-in tools are great, the dateutil library excels at parsing date strings from various formats. The parser.parse() function can intelligently figure out the date from a string without you needing to define the format first.
- It automatically recognizes common formats, like
"Oct 24, 2023"in the example. - This saves you from the tedious work of handling every possible date format with
strptime().
It's especially useful when you're working with data from external sources where date formats can be inconsistent.
Move faster with Replit
Replit is an AI-powered development platform where you can start coding Python instantly. It comes with all Python dependencies pre-installed, so you can skip the setup and focus on building. While knowing how to use tools like strftime() and timedelta is useful, building a full application is the next step.
With Agent 4, you can move from piecing together techniques to creating complete, working software. Instead of just writing code, you can describe the app you want to build, and the Agent will handle the rest. Here are a few examples of what you could create:
- A personal event countdown that calculates the days remaining to a future date.
- A timezone conversion tool that displays the current time in multiple cities around the world.
- A utility that parses various date formats from a text file and standardizes them into a single format.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Working with dates can sometimes lead to tricky errors, but understanding the common pitfalls makes them much easier to solve.
- Debugging
TypeErrorwhen comparing dates: You'll encounter aTypeErrorif you try comparing a "naive"datetimeobject (without timezone info) to an "aware" one (with it). Python can't reconcile the two, so you must make them consistent by either adding or removing timezone information before the comparison. - Avoiding errors when parsing date strings: The
strptime()method raises aValueErrorif the format string doesn't perfectly match the input. Ensure every code, like%Y, and separator, like a hyphen or space, in your format string exactly mirrors the date string you're parsing. - Extracting days from
timedeltacorrectly: It's easy to misinterpret the.daysattribute on atimedeltaobject, as it only returns the full days and ignores leftover hours or minutes. To get a precise total duration in days, use thetotal_seconds()method and divide by 86,400.
Debugging TypeError when comparing dates with different timezones
Comparing a "naive" datetime object (without timezone info) to an "aware" one (with it) will raise a TypeError. Python can't reconcile the two, as one has timezone context and the other doesn't. The code below shows this common error.
from datetime import datetime
import pytz
local_time = datetime.now()
utc_time = datetime.now(pytz.UTC)
if local_time < utc_time:
print("Local time is earlier")
else:
print("UTC time is earlier")
This error occurs because local_time is naive, lacking timezone data, while utc_time is aware. The less-than operator (<) can't compare these different types. See how to resolve this in the corrected version below.
from datetime import datetime
import pytz
local_time = datetime.now()
utc_time = datetime.now(pytz.UTC)
local_time_aware = local_time.replace(tzinfo=pytz.UTC)
if local_time_aware < utc_time:
print("Local time is earlier")
else:
print("UTC time is earlier")
The fix is to make both objects consistent before comparing them. The .replace(tzinfo=pytz.UTC) method attaches timezone information to the naive object, making it "aware." With both objects now having timezone context, Python can perform the comparison without raising a TypeError. You'll often encounter this when working with timestamps from different systems or APIs, where one might provide timezone data and another might not. For more details on various techniques for comparing dates in Python, check out our comprehensive guide.
Avoiding errors when parsing date strings with strptime()
When using strptime(), you'll find it's quite particular. The format string you provide must be an exact mirror of the date string. Even a small difference, like using a slash instead of a dash, will cause a ValueError. See this common error in action below.
from datetime import datetime
date_string = "10/24/2023"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
print(parsed_date)
The error occurs because the format string "%Y-%m-%d" is looking for hyphens, but the input string provides slashes. The structure must match exactly. The following code shows the correct approach.
from datetime import datetime
date_string = "10/24/2023"
parsed_date = datetime.strptime(date_string, "%m/%d/%Y")
print(parsed_date)
The fix is to make the format string an exact match for the date string. By changing the format to "%m/%d/%Y", the code now correctly reflects that the input string uses slashes as separators and is in month-day-year order. This level of precision is essential for strptime() to work correctly. You'll often encounter this challenge when parsing dates from inconsistent sources like CSV files or API responses, so always verify your format string.
Extracting days from timedelta objects correctly
Extracting days from timedelta objects correctly
When you subtract two datetime objects, the result is a timedelta object. While it represents the duration between the dates, simply printing it doesn't just give you the number of days—it often includes hours, minutes, and even seconds.
The following code shows how this can produce unexpected results when you're only interested in the day count.
from datetime import datetime
start_date = datetime(2023, 10, 1)
end_date = datetime(2023, 10, 15)
days_between = end_date - start_date
print(f"Days between: {days_between}")
Printing the days_between object directly gives you a formatted duration string, not the simple integer you probably want. To get just the number of days, you need to access a specific attribute. Check out the corrected code below.
from datetime import datetime
start_date = datetime(2023, 10, 1)
end_date = datetime(2023, 10, 15)
days_between = (end_date - start_date).days
print(f"Days between: {days_between}")
The fix is to access the .days attribute on the timedelta object. By changing the calculation to (end_date - start_date).days, you extract the day count as a simple integer, ignoring any smaller time units. This is the correct approach when you need a whole number for calculations, like figuring out the days left in a trial period or tracking project deadlines. It ensures your logic isn't complicated by unwanted time information.
Real-world applications
Beyond formatting dates and fixing errors, these skills are the foundation for many practical, real-world applications. With AI-powered Python development, you can accelerate the creation of these date-based tools and focus on the business logic rather than implementation details.
Calculating age based on a birthdate with date
Calculating age isn't just a matter of subtracting years; you also need to account for the current day, which can be done with a clever tuple comparison using the less-than operator (<).
from datetime import date
birthdate = date(1990, 5, 15)
today = date.today()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
print(f"Age: {age} years")
This code calculates a person's exact age by determining if their birthday has already occurred this year. It starts with a simple subtraction of the birth year from the current year. The final part of the expression is where the adjustment happens.
- The comparison
(today.month, today.day) < (birthdate.month, birthdate.day)returns a boolean value. - In Python arithmetic,
Trueis treated as the integer1andFalseas0. - This result is then subtracted, correctly reducing the age by one if the current date is before this year's birthday.
For more advanced methods and edge cases when calculating age in Python, explore additional techniques and considerations.
Building a simple date-based reminder system with datetime
With datetime and timedelta, you can build a basic reminder system that calculates the time remaining until a future event.
from datetime import datetime, timedelta
reminders = [
{"task": "Team meeting", "due_date": datetime.now() + timedelta(days=1)},
{"task": "Project deadline", "due_date": datetime.now() + timedelta(days=7)}
]
for reminder in reminders:
days_left = (reminder["due_date"] - datetime.now()).days
print(f"{reminder['task']}: {days_left} days left (due on {reminder['due_date'].strftime('%Y-%m-%d')})")
This snippet shows how to dynamically manage a schedule. It populates a list with tasks, setting their due dates relative to the current moment using datetime.now() and timedelta. The loop then processes each item individually to determine its status.
- A subtraction operation between two
datetimeobjects yields the duration until the deadline. - Accessing the
.daysattribute isolates the number of full days remaining. - The output uses
strftime()to present each due date in a consistent, readable format.
Get started with Replit
Now, turn what you've learned into a real tool. Describe what you want to build to Replit Agent, like “create a timezone converter for major world cities” or “build a simple age calculator from a birthdate.”
Replit Agent writes the code, tests for errors, and helps you deploy the app. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



