Timedelta-python

In this article we will focus on timedelta class of Datetime module.

Datetime module is an important module in python which is used for manipulating dates and time.

Six main classes of Datetime module are:

  1. date

timedelta is used for calculating differences in dates and also used for estimating the past and future date.

It has seven arguments :days, seconds, microseconds, milliseconds, minutes, hours and weeks.

All arguments in timedelta are optional and are initially set to 0.

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

We can select one or multiple arguments from timedelta and set it for specific requirements.This helps in manipulating datetime

In the below cell by setting days =12 ,timedelta object helps in finding date of past 12 days and similarly by setting days = 1 helps in calculating datetime 1 day from now

from datetime import datetime, timedeltacurrent_date = datetime.now()
print("Current Date : ", current_date)
# Subtracting 12 days
past_date = datetime.now() - timedelta(days=12)
print("Past Date: ", past_date)
# Adding 1 day
future_date = current_date + timedelta(days=1)
print("Future Date : ", future_date)

Output of the above cell will be

Current Date :  2022-01-21 18:09:10.212758
Past Date: 2022-01-09 18:09:10.213755
Future Date : 2022-01-22 18:09:10.212758

By this we end this topic and we see that timedelta is useful for calculating past and future dates.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store