add/subtract timedelta to current or specific time – python/django

Sometimes it is required to add/subtract an amount of time to current or any specific time.

We can not add/subtract datetime.timedelta object directly from datetime.time object.

Let’s have an example. Assume that you have any specific time in variable start_time and you want to add 30 minutes to that time. You can do this it as shown below.

You need to import datetime if you didn’t imported yet.

import datetime

Now you have to convert your time object to datetime using combine(). First parameter to combine is a date object and second parameter is time object. It will return a date time object for the input parameters. Now, you can add/subtract timedelta from this datetime object.

Add 30 minutes to any specific time

newTime = (datetime.datetime.combine(datetime.date(1, 1, 1), start_time) + datetime.timedelta(minutes=30)).time()

Subtract 30 minutes

newTime = (datetime.datetime.combine(datetime.date(1, 1, 1), start_time) - datetime.timedelta(minutes=30)).time()

timedelta have options like hours, minutes, seconds, days, weeks

Add timedelta to current time:

import datetime

currentDatetime = datetime.datetime.now()
newTime = currentDatetime + datetime.timedelta(hours=1)

# Get Date:
newTime.date()

# Get Time
newTime.time()

Use Case: current date + Two days

upcomingDate = datetime.datetime.now().date() + datetime.timedelta(days=2)

Use Case:

Let’s assume that you have a database table for sessions/classes. There is a  date field for session date and time field for session start time in the database. You want to apply a condition that user can cancel the session booking before 12 hours of session start time. You get date and time separately and want to combine both to get datetime. You can combine both as shown below:

CREATE TABLE `sessionschedule` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `instructor_id` int(11) NOT NULL,
 `capacity` int(11) NOT NULL,
 `session_date` date NOT NULL,
 `start_time` time(6) NOT NULL,
 `end_time` time(6) NOT NULL,
 `slug` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
sessionScheduleDetails = SessionSchedule.objects.get(slug=session_schedule_slug)

sessionDateTime = (datetime.datetime.combine(sessionScheduleDetails.session_date, sessionScheduleDetails.start_time))

You can get timestamp for the combined date:

sessionDateTime.timestamp()

Get datetime for 12 hours before the Session datetime:

sessionDateTime = (datetime.datetime.combine(sessionScheduleDetails.session_date, sessionScheduleDetails.start_time) - datetime.timedelta(hours=12))

Now you can get timestamp for the sessionDateTime to perform operations like “cancellation is allowed before 12 hours of session time”:

currentTime = datetime.datetime.now()

if currentTime.timestamp() > sessionDateTime.timestamp():
    # error: can cancel schedule booking before 12 hours of the scheduled time.
else:
    # Cancel class booking

You can add week, month, years to current date or any specific date using relativedelta.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares