Hey everyone! I’m working on a project involving Spotify’s track data and I’ve hit a snag. I have a track length given as a decimal value, like 292.96, and I need to display it as minutes and seconds. I’m aiming for a format similar to ‘4:52’.
I’ve experimented with a few methods, but nothing has quite worked out. If anyone has suggestions or code examples that could point me in the right direction, I’d really appreciate it. Thanks a lot!
# Sample code snippet I'm exploring
duration = 292.96
# How can I format this number into a 'minutes:seconds' string?
As someone who’s worked extensively with music streaming APIs, I can share a neat trick I’ve used. While the other solutions work, here’s an alternative approach using the datetime module:
This method is particularly useful if you’re dealing with longer durations or need to handle hours as well. It’s also quite flexible if you need different formatting options later on.
One caveat: this rounds down, so 292.99 would still give you 04:52. If you need more precision, you might want to use round() on the duration first. Hope this helps with your Spotify project!
This function converts the decimal seconds to minutes and remaining seconds, then formats it as a string. The ‘:02d’ ensures the seconds are always two digits. Hope this helps with your project!
This approach rounds the duration to the nearest second before conversion, which can be more accurate for display purposes. The divmod() function efficiently handles the division and modulus operations in one go. It’s a concise and readable solution that should work well for your Spotify track duration formatting needs.