user2989731
user2989731

Reputation: 1359

Python subtract time

I have a value from a database that I believe is in a string format "03:00:00". I want to indicate that this is a time value in python and then use it to set a range (ex. from 02:00:00 to 04:00:00)

I've imported the datetime module, but any time I try and perform an operation on the time value, I receive an internal server error.

from datetime import date, time, timedelta

time_limit = "03:00:00" ## this is actually received as a get response from JS

time_upper_limit = time_limit + timedelta(minutes=60)

The code fails at time_upper_limit. Any idea why this is happening? Do I need to convert the time value?

Upvotes: 0

Views: 2661

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

You cannot sum a string value and a timedelta() object; you can only add timedelta() objects to other timedeltas, datetime objects and date objects.

You'll have to parse the time value first; you probably should parse it to another timedelta() object (as a duration):

hours, minutes, seconds = map(int, time_limit.split(':'))
time_limit = timedelta(hours=hours, minutes=minutes, seconds=seconds)

Now you can add another timedelta() object to it:

time_upper_limit = time_limit + timedelta(minutes=60)

Demo:

>>> from datetime import timedelta
>>> time_limit = "03:00:00"
>>> hours, minutes, seconds = map(int, time_limit.split(':'))
>>> time_limit = timedelta(hours=hours, minutes=minutes, seconds=seconds)
>>> time_limit
datetime.timedelta(0, 10800)
>>> time_limit + timedelta(minutes=60)
datetime.timedelta(0, 14400)

The alternative would be to parse this to a datetime.datetime object, e.g. add a date to the time; datetime.time() objects cannot be used with timedelta() objects because they cannot go beyond 23:59:59.999999, while timedelta() objects can easily model periods longer than a day:

>>> from datetime import datetime
>>> time_limit = "03:00:00"
>>> dt = datetime.strptime(time_limit, '%H:%M:%S')
>>> dt
datetime.datetime(1900, 1, 1, 3, 0)
>>> dt + timedelta(minutes=60)
datetime.datetime(1900, 1, 1, 4, 0)

As you don't have a date component in your string, you end up with the date 1900-01-01 in the resulting value. You could ignore that issue and work with just the time component, or you can use datetime.datetime.combine() and datetime.datetime.time() to extract the time component and replace the date with another that suits your needs better (such as datetime.date.today()).

Upvotes: 1

Related Questions