Python Datetime: A Quick Tutorial with Examples

Module Python

Python’s datetime module is an essential tool for handling dates and times in your code. It provides classes to work with date, time, and even more complex objects like timedelta (a duration of time). This guide will cover the basics of using Python’s datetime module.

Table of Contents

Understanding Datetime Objects

The datetime object represents a single point in time. It consists of two parts: date and time. The date part is represented by date class, while the time part is represented by time class.

Here’s how you can create a datetime object:


from datetime import datetime

# Current date and time
now = datetime.now()
print(now)

# Specific date and time
custom_date = datetime(2024, 1, 1, 10, 30)
print(custom_date) # Output: 2024-01-01 10:30:00

Working with Dates

The date class in Python’s datetime module represents a date (year, month and day). Here are some methods you can use:


from datetime import date

# Current date
today = date.today()
print(today)

# Specific date
custom_date = date(2025, 1, 1) # Output: 2025-01-01
print(custom_date)

Working with Times

The time class in Python’s datetime module represents a time (hour, minute, second and microsecond). Here are some methods you can use:


from datetime import time

# Specific time
custom_time = time(12, 30)
print(custom_time) # Output: 12:30:00

Manipulating Dates and Times

You can manipulate dates and times using the timedelta class. It represents a duration, the difference between two times or dates. Here’s how you can use it:


from datetime import date, datetime, timedelta

# Create a timedelta object representing 1 day
one_day = timedelta(days=1)
print(one_day)

# Add one day to the current date
today = datetime.today()
tomorrow = today + one_day
print(tomorrow)

Formatting Dates and Times

You can format dates and times using the strftime method:


from datetime import datetime

# Current date and time
now = datetime.now()

# Format as string
formatted_date = now.strftime("%Y-%m-%d %H:%M")
print(formatted_date)  # Outputs: 2025-02-05 12:36 (my current time)

Parsing Dates and Times

You can parse strings into datetime objects using the strptime method:


from datetime import datetime

# String to parse
date_string = "2024-01-01 10:30"

# Parse string into a datetime object
parsed_datetime = datetime.strptime(date_string, "%Y-%m-%d %H:%M")
print(parsed_datetime)

Conclusion

Python’s datetime module is a powerful tool for handling dates and times in your code. It provides classes to work with date, time, and even more complex objects like timedelta (a duration of time). With the right understanding and usage, you can create robust applications that handle date-time related tasks effectively.

To top