13

I'd like to store an amount of time for something in a mysql database,for the length of time something took, such as 2 hours, 5 minutes, 10 seconds. accuracy down to the second is preferred, but not required. What's the best way to go about doing this?

3
  • 2
    The purpose may make a difference here; if storing an integer number of seconds is adequate for you, that may be the way to go. I have not checked the mysql documentation in a while, but I do not recall mysql having a timespan data type.
    – Andrew
    Oct 5, 2010 at 20:49
  • 2
    I don't know the particulars of MySQL, but in my experience, if all you need is "to the second" precision, then storing TotalSeconds makes the most sense. It is generally much easier to parse that value back to any given time format, rather than having code to parse, say a string like "00:00:00" to an intermediary format first. Oct 5, 2010 at 20:52
  • good point @Andrew. I was going to go with the TIME type after looking at some of the answers, but after thinking about how it will be implemented in the application, integer w/ seconds makes more sense (lots of math/comparison going on with times).
    – GSto
    Oct 5, 2010 at 20:58

3 Answers 3

20

A MySQL TIME type can store time spans from '-838:59:59' to '838:59:59' - if that's within your required range, and it would be useful to have MySQL natively present these spans in HH:MM:SS form, then use that.

Otherwise, I'd just go with an integer type to represent the number of seconds.

3

I like storing things in the database as base units. That way I can reliably and accurately convert to anything else I want later on.

The only thing you have to worry about with this method is getting your precision down. If you are storing distance traveled for cross country trips, inches or centimeters might not be what you are looking for.

In your case, I'd store the span as seconds or milliseconds and go from there.

1

As Andrew says, an integer field with seconds might do already.

If the data is available, and it makes sense to store it, I would save the data in two mySQL timestamps with the start and end times (also possibly great for auditing later), and use DATE_DIFF() to fetch the actual duration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.