Incorrect time display when using time.localtime()

59 Views Asked by At

Good afternoon! I started to develop mp3-player, and faced with incorrect time display when using time.localtime.

I put the current time of playing a song into the current_time variable, and the total duration of the song into the song_duration variable.

current_time = time.strftime('%H:%M:%S', time.localtime(self.player.position() / 1000))
print(time.localtime(self.player.position() / 1000))
song_duration = time.strftime('%H:%M:%S', time.localtime(self.player.duration() / 1000))
print(time.localtime(self.player.duration() / 1000))
self.ui.start_lbl.setText(f"{current_time}")
self.ui.end_lbl.setText(f"{song_duration}")

The problem is that the current and remaining time are displayed incorrectly - namely, two extra hours are taken from somewhere (although the song is 4 minutes long). enter image description here

I double-checked: time.localtime actually set tm_hour as "2", although the minutes and seconds were calculated correctly (the calculation is based on the player's position). enter image description here

Here is the code of the player's own declaration:

self.player = QMediaPlayer()
self.audio_output = QAudioOutput()
self.player.setAudioOutput(self.audio_output)

I'm new to the topic of working with audio files, so please advise me what needs to be fixed.

I'm trying to understand what exactly was done wrong. The player setup itself is obviously correct: the song plays correctly, and the minutes and seconds in both cases (current time and total time) are shown correctly.

1

There are 1 best solutions below

1
Moaybe On
def format_duration(milliseconds):
    # Convert milliseconds to seconds
    total_seconds = int(milliseconds / 1000)
    hours = total_seconds // 3600
    minutes = (total_seconds % 3600) // 60
    seconds = total_seconds % 60

    # Format time as HH:MM:SS
    return f"{hours:02}:{minutes:02}:{seconds:02}"

# Use the format_duration function to format the current time and song duration
current_time = format_duration(self.player.position())
song_duration = format_duration(self.player.duration())

self.ui.start_lbl.setText(current_time)
self.ui.end_lbl.setText(song_duration)