Search code examples
postgresqltype-conversiondata-conversion

How to extract the integer value of a time formatted as "MI:SS"


I would like to import an Excel file in which times are formatted as "00:00" (minutes:seconds). The corresponding field in the database is designated as an integer.

Which function can I use to enter the value and convert it to the corresponding integer representation? For example: "02:39" should return "159".

I attempted to google as well as look at various sources like: https://www.postgresql.org/docs/current/functions-datetime.html. I couldn't find the function I needed


Solution

  • This is possible with some date arithmetic:

    select extract('epoch' from interval '00:02:39');
    

    Extracting 'epoch' from a time or interval value gives the number of seconds in the interval. In your case (mm:ss), you need to prepend '00:' or the literal is read as hh:mm. The hh, mm, and ss fields are limited to 0-23 and 0-59 resp. (for intervals, the hour field can be greater than 23).

    Features depend on the Postgresql version, I have used 16. Here is a fiddle with a slightly more elaborate example.