Skip to content
PythonData, APIs, and Concurrencybeginner30 min read

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

Create and inspect date and time objects
python
from datetime import date, datetime, time, timedelta
 
birthday = date(2004, 8, 12)
meeting_time = time(14, 30, 0)
meeting = datetime(2026, 1, 15, 14, 30)
duration = timedelta(hours=2)
 
print(birthday)
print(meeting_time)
print(meeting)
print(duration)
Output
2004-08-12 14:30:00 2026-01-15 14:30:00 2:00:00

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

A date object cannot store a clock time. A time object cannot store a calendar date. Use datetime when both pieces of information belong together.

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

Get the current local date and time
python
from datetime import date, datetime
 
current_date = date.today()
current_datetime = datetime.now()
 
print(current_date)
print(current_datetime)
Output
The output depends on 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

The operating system clock, configured time zone, and execution time affect current-date examples. Use fixed values when an exercise requires an exact output.

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

Move a date forward and backward
python
from datetime import date, timedelta
 
start = date(2025, 12, 31)
next_day = start + timedelta(days=1)
previous_day = start - timedelta(days=1)
 
print(next_day)
print(previous_day)
Output
2026-01-01 2025-12-30

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

A timedelta represents a duration, not a calendar month. A month may contain 28, 29, 30, or 31 days, so adding one month requires a separate calendar-aware approach.

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

Format a date in different styles
python
from datetime import date
 
day = date(2025, 5, 4)
 
print(day.strftime('%d-%m-%Y'))
print(day.strftime('%Y/%m/%d'))
print(day.strftime('%B %d, %Y'))
Output
04-05-2025 2025/05/04 May 04, 2025

%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

Format codes are case-sensitive. For example, %m means month, while %M means minute.

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

Convert text into a datetime
python
from datetime import datetime
 
text = '04-05-2025'
parsed = datetime.strptime(text, '%d-%m-%Y')
 
print(parsed)
print(parsed.year)
print(parsed.month)
print(parsed.day)
Output
2025-05-04 00:00:00 2025 5 4

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

Do not confuse strftime() and strptime(): strftime() formats an existing date/time object as text; strptime() parses text into a datetime object.

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

Parse and produce ISO-style dates
python
from datetime import date, datetime
 
day = date.fromisoformat('2026-01-15')
meeting = datetime.fromisoformat('2026-01-15T14:30:00')
 
print(day.isoformat())
print(meeting.isoformat())
Output
2026-01-15 2026-01-15T14:30:00

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

An ISO-formatted value is not automatically time-zone-aware. Inspect whether a time-zone offset or other time-zone information is present before treating a date-time as a specific global moment.

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

Create an aware UTC datetime
python
from datetime import datetime, timezone
 
moment = datetime(2026, 1, 15, 9, 0, tzinfo=timezone.utc)
print(moment.isoformat())
print(moment.tzinfo is timezone.utc)
Output
2026-01-15T09:00:00+00:00 True

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

Avoid treating a naive datetime as UTC unless your application explicitly defines that convention. When recording globally meaningful event times, prefer aware UTC values and convert them for display.

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

Trace a deadline calculation
python
from datetime import date, timedelta
 
start = date(2026, 1, 28)
deadline = start + timedelta(days=5)
print(deadline.strftime('%d-%m-%Y'))
Output
02-02-2026

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

The date arithmetic and formatted output above are deterministic because the example uses fixed values rather than the current clock.

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

Use the correct month and minute directives
python
from datetime import datetime
 
value = datetime(2026, 7, 9, 16, 5)
print(value.strftime('%m'))
print(value.strftime('%M'))
Output
07 05

%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

Other important boundaries include leap years, invalid calendar dates, negative durations, month-end calculations, daylight-saving transitions, and the distinction between naive and aware datetimes.

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.

Incorrect Approach
script.py
python
Treating a date string as if it were a date object.
Correct Solution
script.py
python
Parse the string with an appropriate method such as date.fromisoformat() or datetime.strptime() before doing 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.

Incorrect Approach
script.py
python
Confusing strftime() with strptime().
Correct Solution
script.py
python
Use strftime() to format an object as text and strptime() to parse text into a datetime object.

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.

Incorrect Approach
script.py
python
Using %m for minutes or %M for months.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Assuming every month contains 30 days.
Correct Solution
script.py
python
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.

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.

Incorrect Approach
script.py
python
Assuming a naive datetime identifies a global moment.
Correct Solution
script.py
python
Use aware datetimes when time-zone identity matters. UTC-aware values are a useful default for globally coordinated event timestamps.

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.

Incorrect Approach
script.py
python
Assuming current-time examples have a fixed output.
Correct Solution
script.py
python
Treat date.today() and datetime.now() output as runtime-dependent. Use fixed constructors in examples and tests that need exact expected results.

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.

Incorrect Approach
script.py
python
Ignoring invalid date input.
Correct Solution
script.py
python
Handle ValueError when parsing external or user-provided dates, and validate the format expected by your application.

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.

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?
Answer:
date represents a calendar date, time represents a clock time without a date, datetime combines a date and time, and timedelta represents a duration or difference between dates or datetimes.
Q2:What is the difference between strftime() and strptime()?
Answer:
strftime() formats an existing date/time object into text. datetime.strptime() parses text according to a format string and returns a datetime object.
Q3:How do you add seven days to a date?
Answer:
Import date and timedelta, create the date, and add timedelta(days=7). For example, date(2026, 1, 1) + timedelta(days=7) produces 2026-01-08.
Q4:What does subtracting two dates return?
Answer:
It returns a timedelta object. Use its days attribute to access the whole-day difference between the dates.
Q5:How do you get the current date and time?
Answer:
Use date.today() for the current local date and datetime.now() for the current local date and time. For the current UTC time as an aware datetime, use datetime.now(timezone.utc).
Q6:What is the difference between naive and aware datetimes?
Answer:
A naive datetime lacks usable time-zone information. An aware datetime includes time-zone information sufficient to identify its relationship to UTC. Aware values are important when coordinating real-world events across locations.
Q7:Why can parsing a date string fail?
Answer:
The text may not match the specified format, or it may contain an impossible date. Python raises ValueError when it cannot parse the input into a valid datetime.
Q8:How do you format a date as YYYY-MM-DD?
Answer:
Use strftime('%Y-%m-%d') on a date or datetime object. The directives represent the four-digit year, two-digit month, and two-digit day.
Q9:Why should applications often store timestamps in UTC?
Answer:
UTC provides a common reference for coordinating events across locations. Applications can convert aware UTC timestamps into users' local time zones for display. The application still needs to define how to handle date-only values and recurring local schedules.
Q10:Why is adding 30 days not the same as adding one month?
Answer:
Months have different lengths, and February varies in leap years. timedelta(days=30) adds exactly 30 days, whereas adding a calendar month requires an explicit rule for dates near the end of a 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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: