Aakash Patel
Aakash Patel

Reputation: 274

Adding time in timefield

I have a model which contains the following field

time_start = models.TimeField(u"Start Time", blank=False)

I want to add 1hr in start time and save it in a list

Here is what I have tried

import datetime as dt
start_time = Timeslot.objects.get(pk=1)
start = start_time.time_start
print(start)
a = (start+dt.timedelta(hours=1)).time()
print(a)
li = []
li.append(a)

but I am getting error

unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

Upvotes: 2

Views: 1984

Answers (2)

Deniz Kaplan
Deniz Kaplan

Reputation: 1609

You can also use combine method for this.

(dt.datetime.combine(dt.date(1,1,1), start) + dt.timedelta(hours=1)).time()

This code will return datetime.time object as you needed.

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

Replacing the hour parameter

Since a time object has a range from 00:00 to 23:59. In case you add one hour, it can thus get out of range, and hence it is no longer a time object.

We can however implement this with wraparound (this means that for example 23:59 and two minutes is 00:01) ourselves, like:

a = start.replace(hour=(start.hour+1) % 24)

We here thus replace the hours of the start (we are not replacing it on the start object, but create a copy) with (start.hour + 1) % 24. The modulo 24 is necessary to make perform the wraparound.

Storing a timestamp in a DateTimeField

The above is however not a nice way to do this: typically time depends on the timezone (location) and the specific date (for example daylight saving time, some countries have changed the timezone, etc.).

Therfore I advice you to use a DateTimeField instead of a TimeField. For example in october 28, 2018 some parts of the world enter daylight saving time, and that means that if you add one hour, the clock can in some cases, still display the same numbers. With a TimeField, this context is lost: we will change the numbers of the clock, regardless what the time is, and what the specific laws of the culture of the user are saying.

Upvotes: 3

Related Questions