The Python Programmer’s Guide to Working with Dates and Times

Max N
2 min readApr 7, 2024

Need to work with dates, times, and calendars in your Python programs? No problem! Python has a built-in module called datetime that makes it easy to work with all things date and time related.

In this article, we'll explore some of the most common use cases for the datetime module and provide practical code examples you can use in your own projects.

Getting Started with datetime

The datetime module provides several classes for working with dates and times, including date, time, datetime, and timedelta. The date class represents a specific calendar date, the time class represents a specific time of day, the datetime class represents a specific date and time, and the timedelta class represents a duration of time.

Here’s a simple example of how to create a date object:

from datetime import date

# Create a date object for April 7, 2024
today = date(2024, 4, 7)
print(today) # Output: 2024-04-07

You can also create datetime objects, which include both a date and a time:

from datetime import datetime

# Create a datetime object for April 7, 2024 at 12:00 PM
now = datetime(2024, 4, 7, 12, 0, 0)
print(now) # Output: 2024-04-07 12:00:00

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.