How to insert a time range in SQL? - sql

So I have a field,
,Time_ TIME NULL
And this field is meant to represent the time a lecture would take place. In this case, the lecture would take place between 1:00 and 2:00. Is it possible to insert this time range or would I only be able to insert a starting time? i.e.
,'1:00PM'
Thanks for the help!

Is it possible to insert a time range into a single field? Yes.
Is it possible to insert a time range into a field formatted as TIME? No.
Is it a good idea to store two data points in one field? Absolutely not.
Am I going to suggest any ways that you COULD store both in one field? Sorry, but no, I'm afraid I'm not.
You'll run into problems parsing the field. You'll run into problems calculating the length of a lecture. You'll just run into problems every time you turn around.
I imagine you want to display the something like "Math 101, 11:00-12:00", and that's fine. In your presentation layer, be it an SSRS report, a spreadsheet, a web page, what have you, call for the class name, the start time, and the end time, then format them appropriately at the output stage. It keeps your data manageable for the next use case.

You cannot insert a time range. If you need to know the range of the lecture you could create columns for 'lecture_starttime' and 'lecture_endtime'.

I would recommend storing both times and calculating the length:
start_time
end_time
This will cater for lectures that aren't always 1 hour long. You can calculate the length as end_time - start_time.

Related

Using Optaplanner for long trip planning of a fleet of vehicles in a Vehicle Routing Problem (VRP)

I am applying the VRP example of optaplanner with time windows and I get feasible solutions whenever I define time windows in a range of 24 hours (00:00 to 23:59). But I am needing:
Manage long trips, where I know that the duration between leaving the depot to the first visit, or durations between visits, will be more than 24 hours. So currently it does not give me workable solutions, because the TW format is in 24 hour format. It happens that when applying the scoring rule "arrivalAfterDueTime", always the "arrivalTime" is higher than the "dueTime", because the "dueTime" is in a range of (00:00 to 23:59) and the "arrivalTime" is the next day.
I have thought that I should take each TW of each Customer and add more TW to it, one for each day that is planned.
Example, if I am planning a trip for 3 days, then I would have 3 time windows in each Customer. Something like this: if Customer 1 is available from [08:00-10:00], then say it will also be available from [32:00-34:00] and [56:00-58:00] which are the equivalent of the same TW for the following days.
Likewise I handle the times with long, converted to milliseconds.
I don't know if this is the right way, my consultation would be more about some ideas to approach this constraint, maybe you have a similar problematic and any idea for me would be very appreciated.
Sorry for the wording, I am a Spanish speaker. Thank you.
Without having checked the example, handing multiple days shouldn't be complicated. It all depends on how you model your time variable.
For example, you could:
model the time stamps as a long value denoted as seconds since epoch. This is how most of the examples are model if I remember correctly. Note that this is not very human-readable, but is the fastest to compute with
you could use a time data type, e.g. LocalTime, this is a human-readable time format but will work in the 24-hour range and will be slower than using a primitive data type
you could use a date time data tpe, e.g LocalDateTime, this is also human-readable and will work in any time range and will also be slower than using a primitive data type.
I would strongly encourage to not simply map the current day or current hour to a zero value and start counting from there. So, in your example you denote the times as [32:00-34:00]. This makes it appear as you are using the current day midnight as the 0th hour and start counting from there. While you can do this it will affect debugging and maintainability of your code. That is just my general advice, you don't have to follow it.
What I would advise is to have your own domain models and map them to Optaplanner models where you use a long value for any time stamp that is denoted as seconds since epoch.

Should I store both birthday and age?

Im making an app that uses both birthday and age to make some deductions,
but as the age can be obtain through the birthday and current date, Im questioning if I should be storing them both and not just the date, for one part I could use the age attribute to simplify some querys without converting dates, what would be the right thing to do following conventions?
Calculations based on data should be always... calculated, not stored. Well, not always, usually, but
it depends on situation. Below are couple of pros and cons:
Cons
calculation logic might change, so stored values will be no loner valid.
or invalid data could be entered (and you will receive invalid data when querying).
or the result changes with time, as age does, eg. today you have 20 years, but in one year you will have 21.
Pros
however, as #RonenAriely mentioned, storing calculated data in order to gain performance is one of pros of such approach.
So, to sum up, you should make calculations, like DATEDIFF(NOW(), DateOfBirth) to get an age, as the result changes in time and the function don't influence performance much.
I would say store just the DOB and calculate the age when using.
I mainly prefer this because age will continuously change and you have to make sure to update it depending on how accurately you are measuring it. This will kind of beat the purpose of computing once and using multiple times because you'll be recomputing a lot of times. Then since it is redundant it'll also unnecessarily occupy space in your tables.
Hope it helped
Generally only birth date is stored.
You can create a common helper method to calculate age. Preferably static to avoid additional memory consumption.
Also saving age in database makes less sense as in such a case you would be required to run a daily cron to see which user's age is increasing by 1 that day and then update in the database.
As said here,
you have to ensure that it is not possible for the derived value to
become out-of-date undetected.
Birthday never goes out-of-date so you would be OK!
Better to follow the normalised approach and only store date of birth. Age would be marginally quicker to retrieve but, for that to be correct, you'd have to refresh the table on a daily basis.
If you were running a DB search on age range, then you could convert min and max ages to an upper and lower date of birth based on the current date and then search accordingly.

How to make a query that computes the difference of two timefield objects/attributes in Django?

Suppose I have a model that has four attributes:
name,
time in,
time out,
date.
time in and time out are timefield objects. Now, I want to write a django query that tells me who was available in the office for most time duration in a given range.
I am not sure how do I calculate the time difference (time out - time in) on the fly. Do I need to put another attribute like time duration? I was hoping to avoid that.
I don't think it's possible using vanilla Django ORM.
Two solutions come to my mind:
Fetch the results in RAM and do the computation.
Add a new field to take care of the duration into your model. You can first do an update query to calculate the duration for all rows in your db.
Class.objects.update(duration=F('time_out')-F('time_in'))
And then you can order_by duration and get the first entry as your max duration.

When to use separate date and time instead of a single datetime

If I want to store date and time, is it better to store them in a separate date and time or use a single datetime?
When should we use date and time instead of a single datetime?
I want to filter my queries either using date or time.
When you are talking about a moment in time, whether a universal moment, or a specific date and time on someone's local calendar, you use a datetime. If you want to be sure that you are talking about an exact moment in time, regardless of the observer, then you use a datetimeoffset.
If you are storing just a date then you mean a date without a time component, meaning "any time on this date".
If you are storing just a time then you mean a time without a date component, meaning "this time on any date", or "this time on a date determined by some other means".
There is no practical purpouse to having both a date and a time that are about the same thing, sitting on the same row. Just use a datetime for that.
In SQL Server 2008 you have date and time data types so this becomes a non issue.
If it is good choice it really depends by your business and how you will query you data.
If for example you want to know all the orders places between 1 and 2 PM for any day using a separated Date and Time column will make it quicker
If you intentionally do not care about the time, it's more efficient to store this data as a date datatype. Think a customer birthday column, there's not too many cases I can think of that would use this time. If there happens to be a time attached to it (often a bug), this needs to be removed via a convert statement in order to do a compare. It also consumes additional space if you don't need these values (3 bytes compared to 8).
I think it's similar to having a status code table with the id as a bigint instead of a tinyint or the like (depending on how many status codes you would plan to have).
It's just a matter of what you're using the data for, if you think there's a good chance you'll ever need the that data, then use datetime, otherwise use date.
Nothing brilliant about separating date and time,
Better you save date and time in Same column,
Here they have discussed the same issue check it : are-there-any-good-reasons-for-keeping-date-and-time-in-separate-columns
you can also get date and time separately by query
SELECT
CONVERT(VARCHAR(10),GETDATE(),111) as DatePart,
convert(varchar(15), getdate(), 108) TimePart

How to calculate blocks of free time using start and end time?

I have a Ruby on Rails application that uses MySQL and I need to calculate blocks of free (available) time given a table that has rows of start and end datetimes. This needs to be done for a range of dates, so for example, I would need to look for which times are free between May 1 and May 7. I can query the table with the times that are NOT available and use that to remove periods of time between May 1 and May 7. Times in the database are stored at a fidelity of 15 minutes on the quarter hour, meaning all times end at 00, 15, 30 or 45 minutes. There is never a time like 11:16 or 10:01, so no rounding is necessary.
I've thought about creating a hash that has time represented in 15 minute increments and defaulting all of the values to "available" (1), then iterating over an ordered resultset of rows and flipping the values in the hash to 0 for the times that come back from the database. I'm not sure if this is the most efficient way of doing this, and I'm a little concerned about the memory utilization and computational intensity of that approach. This calculation won't happen all the time, but it needs to scale to happening at least a couple hundred times a day. It seems like I would also need to reprocess the entire hash to find the blocks of time that are free after this which seems pretty inefficient.
Any ideas on a better way to do this?
Thanks.
I've done this a couple of ways. First, my assumption is that your table shows appointments, and now you want to get a list of un-booked time, right?
So, the first way I did this was like yours, just a hash of unused times. It's slow and limited and a little wasteful, since I have to re-calculate the hash every time someone needs to know the times that are available.
The next way I did this was borrow an idea from the data warehouse people. I build an attribute table of all time slots that I'm interested in. If you build this kind of table, you may want to put more information in there besides the slot times. You may also include things like whether it's a weekend, which hour of the day it's in, whether it's during regular business hours, whether it's on a holiday, that sort of thing. Then, I have to do a join of all slots between my start and end times and my appointments are null. So, this is a LEFT JOIN, something like:
SELECT *
FROM slots
WHERE ...
LEFT JOIN appointments
WHERE appointments.id IS NULL
That keeps me from having to re-create the hash every time, and it's using the database to do the set operations, something the database is optimized to do.
Also, if you make your slots table a little rich, you can start doing all sorts of queries about not only the available slots you may be after, but also on the kinds of times that tend to get booked, or the kinds of times that tend to always be available, or other interesting questions you might want to answer some day. At the very least, you should keep track of the fields that tell you whether a slot should be one that is being filled or not (like for business hours).
Why not have a flag in the row that indicates this. As time is allocated, flip the flag for every date/time in the appropriate range. For example May 2, 12pm to 1pm, would be marked as not available.
Then it's a simple matter of querying the date range for every row that has the availability flagged set as true.