Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46208

Django - Datetime range end time excluded

I did a form to allow users to add absences consisting of datetime ranges.

datetime range editor

I left the time optional, so they can set for example 2014-01-23 to 2014-01-24

But since the final stored values will be 2014-01-23 00:00:00 to 2014-01-24 00:00:00, this range will actually cover only the 23rd. Most likely the user will want us to consider 2014-01-25 00:00:00 instead for the end.

Is it a good idea to store these datetimes this manner ?

Should I automatically increment the end date if end time is not set ?


Update

Following @MartijnPieters advice, here is how I checked wether end_time was empty

def clean_end_time(self):
    end_dt = self.cleaned_data.get('end_time', None)
    if end_dt.time().min == end_dt.time():
        return datetime.combine(end_dt, end_dt.time().max)
    return self.cleaned_data.get('end_time', None)

The only small issue will be that the user can't select 00:00 as end_time on purpose

Upvotes: 0

Views: 470

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124170

Set the end time to 23:59:59.999999 if the time is not set, instead.

Now your datetime range goes from 2014-01-23 00:00:00 through to 2014-01-24 23:59:59.999999, 1 microsecond before 2014-01-25 (which is not part of the range).

Your can use datetime.time.max to provide this value:

end = datetime.datetime.combine(datetime.date(2014, 1, 24), datetime.time.max)

Upvotes: 3

Related Questions