Adventures in Machine Learning

Simplifying Date and Time Manipulation in Python

Working with Dates and Time in Python

Time is a critical element in our lives, and as humans, we organize our daily activities around it. From meeting schedules to deadlines, time plays a vital role in decision-making.

In the world of programming, the accurate handling of dates and time is crucial for designing effective applications. In this article, we will explore the datetime module and the timedelta module and how they simplify working with dates and time in Python.

Overview of datetime module

In Python, the datetime module is a built-in library that facilitates the syntax and calculations needed when dealing with date and time objects. It allows us to manipulate different aspects of time such as the year, month, day, hour, minute, and second.

This module consists of two major classes: the date class and the time class. Let’s look at each one in detail:

Date class – The date class deals with formatting and manipulating date objects, which carry year, month, and day information.

We can use this class for tasks such as calculating the time difference between two dates or adding or subtracting days from a date. Each date object comes with various attributes such as year, month, and day which allows for flexible and customizable formatting.

Time class – The time class deals with handling time objects. It carries hour, minute, second, and microsecond attributes.

We use the time class to represent time as a fraction of one day. This class allows for easy manipulation of time values, including addition and subtraction of time elements.

Libraries used for manipulating dates and time

Working with dates and time involves manipulating data, which comprises numerous operations. Python provides two fundamental libraries used for manipulating dates and time:

Datetime module – The datetime module packages most of the functionality of the date and time classes mentioned above.

It enables developers to parse strings into date and time objects, format date and time objects, compare dates and times, and calculate the time difference between two dates. The datetime module also allows customizations, such as defining the weekday of a particular date.

Timedelta module – The timedelta module provides functionality to perform arithmetic on date and time objects. We can express arithmetic operations such as subtraction, addition, and multiplication with time intervals.

For example, we can use timedelta to add or subtract days, hours, minutes, or seconds from a datetime object.

Examples of adding days to dates

One of the most common operations developers perform is adding or subtracting days from a given date. Let’s explore some examples of how to add days to a date using the datetime module and timedelta:


from datetime

import datetime, timedelta

now =

print(“Today’s date:”, now)

# Adding 5 days to current date

new_date = now + timedelta(days = 5)

print(“Date after adding 5 days:”, new_date)

# Adding 1 week to the current date

new_date = now + timedelta(weeks = 1)

print(“Date after adding 1 week:”, new_date)


In the code above, we first import the datetime module and timedelta class.

Then, we create a datetime object representing the current date and time using the datetime function. Our code then prints today’s date.

To add five days from the current date, we create a new datetime object and add five days to it using the timedelta class. We repeat the same steps to add a week to the current date and print the updated date value.

Timedelta allows us to add various metrics such as hours, minutes, and seconds for greater flexibility.

Applications of Adding Days to Dates

Locating files within time constraint

Adding days to a given date is useful when we need to filter or search for files modified within a specific duration. In such cases, we can use the os module to locate files within a specified period.

However, before searching, we convert the date to a timestamp since the os module reads timestamps to compare with files’ creation dates. Below code finds files modified within the last 30 days:


import os

import time

current_time = time.time()

timeframe = 30 * 24 * 60 * 60 # Get 30 days in seconds

list_of_files = []

for dirpath, dirnames, filenames in os.walk(‘./’):

for file in filenames:

file_path = os.path.join(dirpath, file)

if os.path.getmtime(file_path) > current_time – timeframe:


# Stop the os.walk after a recursive call that has run ten times

# to prevent going too deep into the file system which can cause slowness

if len(list_of_files) > 10:




Handling timezones

Dealing with timezones is difficult, but using the datetime module makes it straightforward. The pytz module offers an excellent tool for working with global timezones.

Below is an example of how to convert the current time to US Eastern Time:


from datetime

import datetime

import pytz

eastern = pytz.timezone(‘US/Eastern’)

current_time =



Printing current time, month, and year

To print the current time, month, and year, we first import the datetime module. We can use the now() function of the datetime class to retrieve the current date and time, then utilize the strftime() function to display the required format.

Below is an example:


import datetime

current_time =

print(f’Today is {current_time.strftime(“%A, %B %d %Y”)}’)

print(f’The current time is {current_time.strftime(“%I:%M:%S %p”)}’)


Final thoughts

Accurate and efficient handling of dates and time is critical for software development, especially when applications require frequent updates. Python, with its datetime module and timedelta libraries, simplifies working with dates and time, and allows developers to build better applications.

I hope this article has provided you with the necessary information to work with dates and time more efficiently in Python. In conclusion, this article has provided an in-depth overview of the datetime module and the timedelta module in Python, which are crucial for accurate handling of dates and time in programming.

Using these libraries, developers can manipulate and format date and time data with ease, add days to dates, search for files within a specific timeframe, handle timezones, and print the current time, month, and year. The importance of these libraries in software development cannot be overstated, and their proper utilization can lead to more efficient and accurate applications.

As such, it is crucial for programmers to have a strong foundation in working with dates and time to ensure the success of their projects.

Popular Posts