Back to Python
2026-02-145 min read

Python Date and Time

Learn Python Date and Time step by step with clear examples and exercises.

Title: Mastering Python Date and Time: A full guide for Practical Applications

Why This Matters

Understanding Python's date and time functionalities is essential for numerous applications, including data analysis, web development, system administration, and more. It allows you to work with current dates and times, manipulate them, and convert between different formats. In exams, interviews, or real-world projects, the ability to effectively manage dates and times can save valuable time and prevent errors.

Prerequisites

Before diving into Python's date and time functionalities, you should have a good understanding of:

  1. Basic Python syntax and control structures (if statements, for loops)
  2. Variables and data types
  3. Functions and modules
  4. Understanding the concept of timezones and daylight saving time
  5. Familiarity with common date formats like YYYY-MM-DD, DD/MM/YYYY, MM/DD/YYYY, etc.

Core Concept

Python provides the datetime module to work with dates and times. The primary classes within this module are:

  • datetime.date: Represents a date without time or timezone information
  • datetime.time: Represents a time of day without date or timezone information
  • datetime.datetime: Combines both date and time information, as well as timezone

Creating Date Objects

To create a date object using the date class, you can use the constructor that takes year, month, and day as arguments:

from datetime import date
today = date.today()
print(today)

Creating Time Objects

To create a time object using the time class, you can use the constructor that takes hour, minute, second, and microsecond as arguments:

from datetime import time
current_time = time.now()
print(current_time)

Creating DateTime Objects

To create a datetime object using the datetime class, you can use the constructor that takes year, month, day, hour, minute, second, and microsecond as arguments:

from datetime import datetime
now = datetime.now()
print(now)

Formatting Dates and Times

Python's strftime method can be used to format dates and times in various ways. The method takes a format string as an argument:

from datetime import datetime
current_datetime = datetime.now()
formatted_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)

Common Date and Time Operations

  • Comparing dates: date1 > date2 checks if date1 is later than date2.
  • Adding days to a date: date + timedelta(days=n) adds n days to the date.
  • Subtracting days from a date: date - timedelta(days=n) subtracts n days from the date.
  • Calculating the difference between two dates: date1 - date2 returns the time difference between the two dates.
  • Determining if a year is a leap year:
from datetime import datetime
year = 2023
leap_year = (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))
print("Is the year a leap year?", leap_year)

Worked Example

Let's create a simple program that prints the current date, time, and datetime object. Then, it adds 5 days to the current date, formats both dates as strings, and checks if the current year is a leap year:

from datetime import date, timedelta

Get the current date

current_date = date.today()

print("Current date:", current_date)

Add 5 days to the current date

five_days_later = current_date + timedelta(days=5)

print("Five days later:", five_days_later)

Format both dates as strings

current_date_formatted = current_date.strftime("%Y-%m-%d %H:%M:%S")

five_days_later_formatted = five_days_later.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted current date:", current_date_formatted)

print("Formatted future date:", five_days_later_formatted)

Check if the current year is a leap year

is_leap_year = (current_date.year % 4 == 0) and ((current_date.year % 100 != 0) or (current_date.year % 400 == 0))

print("Is the current year a leap year?", is_leap_year)

Common Mistakes

  1. Forgetting to import the datetime module.
  2. Using the incorrect class (date, time, or datetime) for a specific task.
  3. Misunderstanding the order of arguments in the constructor for creating date and time objects.
  4. Failing to format dates and times correctly using the strftime method.
  5. Not accounting for daylight saving time when working with dates across different time zones.
  6. Incorrectly handling leap years when calculating elapsed time between two dates.
  7. Failing to consider negative values when subtracting datetime objects.

Practice Questions

  1. Write a program that prints the current date, time, and datetime object in various formats (e.g., YYYY-MM-DD, DD/MM/YYYY, MM/DD/YYYY, etc.).
  2. Create a function that takes a date as input and returns the number of days until the next Monday.
  3. Write a program that calculates the elapsed time between two given dates in various formats (e.g., years, months, days).
  4. Modify the worked example to format both dates using a custom format string of your choice.
  5. Create a function that takes a date and returns the corresponding day of the week as a string (e.g., "Monday").
  6. Write a program that calculates the number of days between two given dates, accounting for leap years correctly.
  7. Modify the worked example to handle different time zones by converting the datetime objects to UTC before comparing them.
  8. Create a function that takes a datetime object and returns the corresponding ISO 8601 formatted string (e.g., "2023-03-14T15:29:57+00:00").

FAQ

What is the difference between datetime.date, datetime.time, and datetime.datetime?

  • date represents a date without time or timezone information, time represents a time of day without date or timezone information, and datetime combines both date and time information, as well as timezone.

How can I create a datetime object from a string using Python's datetime module?

  • You can use the strptime function to convert a string into a datetime object: datetime.strptime("date_string", "%format"). Replace "date\_string" with your date as a string, and "%format" with the format of your date string (e.g., "%Y-%m-%d %H:%M:%S").

How can I create a datetime object representing the current date and time in UTC?

  • To create a datetime object representing the current date and time in UTC, use datetime.utcnow().

What is the purpose of Python's timedelta class?

  • The timedelta class represents a duration of time that can be added or subtracted from datetime objects to create new ones.

How can I check if a given year is a leap year using Python's datetime module?

  • You can use the following code to determine whether a year is a leap year:
from datetime import datetime
year = 2023
leap_year = (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))
print("Is the year a leap year?", leap_year)
Python Date and Time | Python | XQA Learn