12

Just a quick question regarding storing "time" in a database. I'm logging the time of users runs which are in the format 00:00:00:00 (hours, minutes, seconds, milliseconds).

I was originally going to store it as TIME but then I realised MySQL doesn't support milliseconds in this type.

I will be storing the actual time taken from the users stopwatch, not the time when they ran and finished (this will be calculated before being inserted).

What would be the best field type to use? I was thinking either double or float, but I'm not sure that would work?

Jack Douglas
  • 40,517
  • 16
  • 106
  • 178
Elliott
  • 297
  • 2
  • 4
  • 8

3 Answers3

7

Personally, I'd use integer types for duration

Example: 340,000 milliseconds is 340000 in an unsigned int column.

To me, datetime, time, date etc are for explicit points in time. 340 seconds is meaningless in that context. Having a start date/time allows the duration to be added of course

gbn
  • 70,237
  • 8
  • 167
  • 244
6

If you use MySQL 5.6.4 or later, you can use the TIME(3), DATETIME(3) and TIMESTAMP(3) column types to store up to 6 fractional digits (replace 3 with the number of fractional digits you need). Fractional part is added to time string after dot; example: 2018-09-08 17:51:04.781.

Official reference

Finesse
  • 221
  • 3
  • 3
2

It depends on how long you want to measure. If you won't be recording any times longer than 2^32, or 4294967296 ms than a regular unsigned int is just fine. That corresponds to about 50 days of clock time, btw.

If you were storing unix time stamps or larger intervals then look at using bigint. This gives you 8 bytes of space, or the ability to record times as long at 1.84467440737096e+19 ms (which is roughly 500 Million years)

atxdba
  • 5,293
  • 5
  • 41
  • 62