Working with Dates and Times
Work confidently with dates, times, durations, parsing, formatting, and time zones using Python's datetime module.
In this lesson, you will learn
- ✓Distinguish between date, time, datetime, and timedelta objects.
- ✓Create date and time objects and obtain the current date or time.
- ✓Add and subtract durations while correctly handling month, year, and day boundaries.
- ✓Format date and time objects with strftime() and parse strings with strptime().
- ✓Recognize ISO-formatted date strings and understand when time zone information is necessary.
- ✓Handle invalid date input and explain common date/time programming mistakes.
1. Understanding Python's date and time types
Python provides several related types through its built-in datetime module. Importing these types lets you work with dates and times as structured values instead of treating everything as an ordinary string.
A date represents a calendar date, such as 2026-01-15. A time represents a clock time, such as 14:30:00, without identifying a particular day. A datetime combines a date and a time. A timedelta represents a duration or difference, such as three days or two hours.
These objects are different from strings. For example, '2026-01-15' is text, whereas date(2026, 1, 15) is a date object. Use a date object for calendar calculations and convert it to a string when you need to display or transmit it.
Create and inspect date and time objects
date(2004, 8, 12) creates a calendar date. The constructor arguments are year, month, and day. time(14, 30, 0) creates a clock time. Python uses the 24-hour clock, so 14 means 2 PM. datetime(2026, 1, 15, 14, 30) combines the date and time. Seconds default to zero. timedelta(hours=2) represents a duration of two hours. Its string representation is 2:00:00.
Note
2. Getting the current date and time
Use date.today() to obtain the current local calendar date. Use datetime.now() to obtain the current local date and time. Their results depend on when and where the program runs, so exact output cannot be predicted in advance.
For repeatable teaching examples and tests, construct a fixed date or datetime explicitly. For production code that records a real moment in time, consider using an aware UTC datetime, shown later in this lesson.
Get the current local date and time
date.today() returns a date based on the system's local date. datetime.now() returns the current local date and time as a naive datetime by default. Do not write a fixed expected timestamp for this example because it changes whenever the program runs.
Note
3. Adding and subtracting durations with timedelta
A timedelta represents a difference in time. You can create one with days, seconds, minutes, hours, weeks, milliseconds, or microseconds. It is useful for deadlines, trial periods, reminders, and elapsed-time calculations.
Adding a timedelta to a date or datetime moves it forward. Subtracting a timedelta moves it backward. Subtracting one date from another produces a timedelta representing the difference between the dates.
Calendar arithmetic automatically handles valid transitions between days, months, and years. For example, adding one day to December 31 crosses into the next year.
Move a date forward and backward
start represents December 31, 2025. Adding one day crosses the year boundary and produces January 1, 2026. Subtracting one day produces December 30, 2025. The original start object is unchanged; date and datetime objects are immutable.
Note
4. Formatting dates with strftime()
The strftime() method converts a date, time, or datetime object into a formatted string. Its format string contains directives beginning with the percent sign (%).
The most useful directives for beginners are %Y for a four-digit year, %m for a zero-padded month, %d for a zero-padded day, %H for a 24-hour clock hour, %M for minutes, and %S for seconds.
Formatting changes the representation used for display; it does not change the date or datetime object itself.
Format a date in different styles
%d produces a zero-padded day, %m produces a zero-padded month, and %Y produces a four-digit year. %B produces the full month name. Month names are locale-sensitive, so localized environments may display different names. strftime() returns a string, making it suitable for display or serialization.
Note
5. Parsing strings with strptime()
Parsing is the reverse of formatting. Use datetime.strptime(text, format) when you receive a date or time as text and need to convert it into a datetime object.
The format must match the input structure. If the string contains a day first, followed by a month and year, the directives must describe that order. Invalid dates and incompatible formats raise ValueError.
Parsing is particularly useful for user input, imported CSV data, and dates received from APIs. Validate input and handle invalid values when your application accepts untrusted or manually entered text.
Convert text into a datetime
The format '%d-%m-%Y' tells Python to interpret the text as day, month, and four-digit year. The result is a datetime object, not a string. Because the input contains no time, the time components default to midnight.
Note
6. ISO date strings and ISO formatting
The ISO-style date format YYYY-MM-DD is widely used in APIs, databases, and data exchange. For example, 2026-01-15 is easy to read and sorts chronologically as text when all values use the same fixed-width format.
Use date.fromisoformat() to parse a supported ISO date string into a date object. Use datetime.fromisoformat() for supported ISO date-time strings. The exact accepted syntax depends on the Python version, so check the official documentation when processing unusual variants.
The isoformat() method converts a date or datetime object into ISO-style text. This is often a good default for exchanging date values, but a date-time string without a time-zone offset does not identify a globally unambiguous instant.
Parse and produce ISO-style dates
date.fromisoformat() parses the date-only string into a date object. datetime.fromisoformat() parses the date and time separated by T. isoformat() returns a string representation. The datetime here has no time-zone information, so it is naive.
Note
7. Time zones and UTC
A naive datetime does not contain enough time-zone information to identify a unique moment globally. An aware datetime includes usable time-zone information. This distinction matters when working with remote users, scheduled events, servers, and APIs.
UTC is a common reference time zone for storing timestamps and coordinating systems. In modern Python, datetime.now(timezone.utc) creates an aware datetime for the current UTC time.
The datetime.timezone class supports fixed offsets, but a fixed offset is not a replacement for a named regional time zone whose rules may change with daylight saving time or legislation. Python's zoneinfo module supports IANA time-zone data on supported platforms and Python versions.
Create an aware UTC datetime
The tzinfo argument associates the datetime with UTC. The +00:00 suffix indicates a zero UTC offset. This example uses a fixed date and time, so its output is deterministic.
Caution
8. Dry run: follow date arithmetic and formatting
A dry run means tracing the program in execution order before running it. Track the value produced by each expression, and distinguish a date object from the formatted string that print() displays.
Trace a deadline calculation
Step 1: start stores January 28, 2026. Step 2: timedelta(days=5) represents five days. Step 3: adding five days produces February 2, 2026. January has 31 days, so the calculation crosses into the next month. Step 4: strftime('%d-%m-%Y') converts the resulting date into day-month-year text. Step 5: print() displays the formatted string.
Note
9. Common mistakes and edge cases
Date and time bugs often occur because text and datetime objects are mixed, format directives are confused, or time-zone assumptions are left unstated. Use explicit types and formats, and validate input from external sources.
Use the correct month and minute directives
%m is the month, so the output is 07. %M is the minute, so the output is 05. Uppercase and lowercase format directives can have different meanings.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Treating a date string as if it were a date object.
Why it happens: A date string is text until parsed; use date.fromisoformat() or datetime.strptime() to obtain a date or datetime object for date arithmetic.
Key takeaway: Parse the string with an appropriate method such as date.fromisoformat() or datetime.strptime() before doing date arithmetic.
#2 Confusing strftime() with strptime().
Why it happens: strftime() formats a date/time object into text, while strptime() parses text according to a specified format.
Key takeaway: Use strftime() to format an object as text and strptime() to parse text into a datetime object.
#3 Using %m for minutes or %M for months.
Why it happens: The format directives are distinct: %m is month and %M is minute, so confusing them changes the displayed result.
Key takeaway: Remember that %m is the month and %M is the minute. Use %H for a 24-hour clock hour and %I for a 12-hour clock hour.
#4 Assuming every month contains 30 days.
Why it happens: Calendar months have different lengths, so use calendar-aware operations when the requirement is a month rather than a fixed 30-day duration.
Key takeaway: Use date arithmetic for day-based durations. For calendar-month arithmetic, define the desired end-of-month behavior and use an appropriate calendar-aware implementation.
#5 Assuming a naive datetime identifies a global moment.
Why it happens: A naive datetime has no timezone information, so it cannot unambiguously identify a moment across time zones.
Key takeaway: Use aware datetimes when time-zone identity matters. UTC-aware values are a useful default for globally coordinated event timestamps.
#6 Assuming current-time examples have a fixed output.
Why it happens: Examples based on the current clock vary over time; tests should use fixed values or control the clock when exact output is expected.
Key takeaway: Treat date.today() and datetime.now() output as runtime-dependent. Use fixed constructors in examples and tests that need exact expected results.
#7 Ignoring invalid date input.
Why it happens: Date parsing can fail for malformed or impossible dates, so validate input and handle ValueError rather than assuming every string is valid.
Key takeaway: Handle ValueError when parsing external or user-provided dates, and validate the format expected by your application.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is the difference between date, time, datetime, and timedelta?
Q2:What is the difference between strftime() and strptime()?
Q3:How do you add seven days to a date?
Q4:What does subtracting two dates return?
Q5:How do you get the current date and time?
Q6:What is the difference between naive and aware datetimes?
Q7:Why can parsing a date string fail?
Q8:How do you format a date as YYYY-MM-DD?
Q9:Why should applications often store timestamps in UTC?
Q10:Why is adding 30 days not the same as adding one month?
Key takeaways
- Use date for calendar dates, time for clock times, datetime for combined date-times, and timedelta for durations.
- Use timedelta to add or subtract day- and time-based durations and to calculate differences between dates.
- Use strftime() to format objects as text and strptime() to parse text into datetime objects.
- Use ISO-style representations for predictable data exchange, while checking whether time-zone information is present when it matters.
- Use aware UTC datetimes for globally coordinated timestamps and convert them for local display.
- Handle ValueError for invalid date input and test boundaries such as month ends, year ends, and leap days.
- Use fixed date/time values for deterministic examples; current-time output changes between runs.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: