Back to Python
2025-12-285 min read

Python datetime

Learn Python datetime step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on Python's datetime module! In this tutorial, we will delve deep into the world of working with dates and times in Python. By understanding the datetime module, you can develop applications that require date or time manipulation, such as scheduling tasks, logging events, or creating data visualizations. Moreover, this knowledge is essential for preparing for interviews and technical assessments where datetime is often tested. Lastly, mastering datetime will help you debug real-world issues related to incorrect date handling in your own projects.

Prerequisites

To follow this tutorial effectively, you should have a basic understanding of Python programming fundamentals (variables, functions, loops, etc.) and be familiar with data structures like lists and dictionaries. If you need a refresher on these topics, consider checking out our previous lessons on Python basics before proceeding.

Core Concept

Python's datetime module offers a rich set of tools for working with dates and times. The main classes are datetime, date, time, and timedelta. These classes provide various methods to manipulate, compare, and format date and time objects. Let's explore each class in detail.

datetime Object

A datetime object represents a specific point in time, including both date and time. It is created using the datetime() function or the datetime.now() method that returns the current date and time.

from datetime import datetime

Create a datetime object for a specific date and time

dt = datetime(2023, 3, 15, 14, 30)

print(dt)

Get the current date and time

now = datetime.now()

print(now)


### date Object
A `date` object represents only a date (no time). It can be created from a `datetime` object or directly using the `date()` function.

Create a date object for March 15, 2023

d = datetime(2023, 3, 15).date()

print(d)

Create a date object directly

dt_obj = datetime(2023, 3, 15, 14, 30)

d = dt_obj.date()

print(d)


### time Object
A `time` object represents only the time part of a date and time (no date). It can be created from a `datetime` object or directly using the `time()` function.

Create a time object for 14:30:00

t = datetime(2023, 3, 15, 14, 30).time()

print(t)

Create a time object directly

dt_obj = datetime(2023, 3, 15, 14, 30)

t = dt_obj.time()

print(t)


### timedelta Object
A `timedelta` object represents a time duration (e.g., days, hours, minutes). It can be created using the `timedelta()` function or by subtracting two `datetime` objects.

Create a timedelta object for 2 days and 3 hours

td = datetime.timedelta(days=2, hours=3)

print(td)

Subtract two datetime objects to get a timedelta

dt1 = datetime(2023, 3, 15, 14, 30)

dt2 = datetime(2023, 3, 17, 9, 0)

td = dt2 - dt1

print(td)

Worked Example

Let's create a simple application that calculates the number of working days between two dates. This example will consider weekends (Saturday and Sunday) as non-working days.

from datetime import datetime, timedelta

def working_days_between(start_date, end_date):
holidays = [datetime(2023, 3, 8), datetime(2023, 3, 25)] # Example holiday list
days = (end_date - start_date).days

for day in range(days + 1):
dt = start_date + timedelta(days=day)
if dt.isoweekday() > 5 or dt in holidays:
days -= 1
return days

start_date = datetime(2023, 3, 15)
end_date = datetime(2023, 4, 15)
print("Number of working days between", start_date, "and", end_date, ":", working_days_between(start_date, end_date))

Common Mistakes

  1. Forgetting to account for holidays or weekends when calculating the number of days between two dates.
  2. Incorrectly formatting date strings when creating datetime objects from them.
  3. Assuming that Python's datetime module behaves similarly to JavaScript's Date object, leading to unexpected results.
  4. Using the wrong function or method for a specific task (e.g., using datetime.now() instead of datetime.utcnow()).
  5. Failing to consider time zones when working with dates across different regions.
  6. Not handling daylight saving time correctly, which can lead to incorrect results when comparing or calculating dates.

Subheadings under Common Mistakes:

  • Incorrect Time Zone Handling
  • Daylight Saving Time Considerations

Practice Questions

  1. Write a function that returns the number of days left until Christmas 2023 (December 25) from the current date.
  2. Given two dates, write a function that determines whether they represent the same day of the week.
  3. Write a function that converts a string representing a date in the format "YYYY-MM-DD" to a datetime object.
  4. Write a function that calculates the age of a person given their birthdate and today's date.
  5. Write a script that calculates the total number of hours worked by an employee who works from 9:00 AM to 6:00 PM, Monday through Friday.

FAQ

Q: How do I format a datetime object as a string?

A: Use the strftime() method to format a datetime object as a string. For example, dt.strftime("%Y-%m-%d %H:%M:%S").

Q: How can I get the current date and time in UTC?

A: Use datetime.utcnow() to get the current date and time in UTC.

Q: What is the difference between a datetime object and a date object?

A: A datetime object includes both date and time, while a date object only represents a specific date (no time).

Q: How do I create a datetime object from a string?

A: Use the strptime() function to create a datetime object from a string representing a date and/or time. For example, datetime.strptime("2023-03-15 14:30:00", "%Y-%m-%d %H:%M:%S").

Q: How do I handle daylight saving time correctly when working with dates?

A: To ensure accurate results, use the tzinfo class to specify a time zone for your datetime objects and consider using the astimezone() method to convert between different time zones.

Q: What is the best way to handle multiple time zones in my application?

A: Consider using a library like pytz, which provides support for various time zones and makes it easier to work with datetime objects across different regions.

Python datetime | Python | XQA Learn