Is there a simple way to convert seconds to HH:MM:SS format in Godot?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Diet Estus

I want to display elapsed playtime on screen. I currently have this time in seconds and want to convert it to HH:MM:SS format.

Is there a simple way to do this in Godot? For example, an in-built function?

:bust_in_silhouette: Reply From: Xrayez

No, I haven’t stumbled upon built-in function for converting seconds into arbitrary time format. Nevertheless, based on a similar question that was asked before, I’ve written a more custom format time function:

enum TimeFormat {
	FORMAT_HOURS   = 1 << 0,

func format_time(time, format = FORMAT_DEFAULT, digit_format = "%02d"):
	var digits = []
	if format & FORMAT_HOURS:
		var hours = digit_format % [time / 3600]
	if format & FORMAT_MINUTES:
		var minutes = digit_format % [time / 60]
	if format & FORMAT_SECONDS:
		var seconds = digit_format % [int(ceil(time)) % 60]
	var formatted = String()
	var colon = " : "
	for digit in digits:
		formatted += digit + colon
	if not formatted.empty():
		formatted = formatted.rstrip(colon)
	return formatted

Where time is in seconds, format can have any combination of values from TimeFormat enum, and digit_format is a default string format for time digits. Returns formatted string time. For instance:

var time = format_time(469, FORMAT_MINUTES | FORMAT_SECONDS)

Thanks! But maybe rstrip() has been removed in Godot 3?

Diet Estus | 2018-09-07 18:42

Was it even present in Godot 2? I’m running (custom build)

This format_time method could be optimized without the use of rstrip though, just don’t add the last colon… figured this should work:

for idx in digits.size():
	formatted += digits[idx]
	if idx != digits.size() - 1:
		formatted += colon

Xrayez | 2018-09-07 18:51

Got it, thanks again! I’ve never used Godot 2, just noticed it wasn’t in Godot 3.0. Have yet to play with 3.1 alpha.

Diet Estus | 2018-09-07 18:56