Sunday, December 22, 2024

MySQL SEC_TO_TIME() Function

 The SEC_TO_TIME() function in MySQL is used to convert a number of seconds into a time format (HH:MM:SS). It returns the time in the format 'HH:MM:SS' based on the number of seconds provided.

Syntax:

SEC_TO_TIME(seconds)
  • seconds: The number of seconds you want to convert into a time format. This can be a positive or negative integer.

Example:

  1. Converting seconds into time format:

    SELECT SEC_TO_TIME(3661);
    

    Output:

    '01:01:01'
    

    (This converts 3661 seconds into 1 hour, 1 minute, and 1 second.)

  2. Using with columns in a table:

    SELECT SEC_TO_TIME(duration_in_seconds) AS formatted_time
    FROM events;
    

    In this case, it converts the duration_in_seconds field from the events table into a time format.

Key Points:

  • The function returns the result as a string in the format 'HH:MM:SS'.
  • It works even with negative values, returning a negative time representation.

If you want to convert a time value back into seconds, you can use the TIME_TO_SEC() function.

No comments:

Post a Comment