Tutorials  /  Python

Simplify Time Conversion: Seconds to Hours, Minutes, and Seconds with Python

Ccentron Redaktion · October 2024 ·5 min read ·Python, Tutorial

Understanding how to work with time conversions is a useful skill when developing various applications. While Python provides built-in modules that handle these conversions easily, it’s a great learning opportunity to first build a custom function yourself. In this tutorial, we'll walk through creating a Python function to convert time in seconds into hours, minutes, and seconds.

Afterward, we'll also explore some of Python’s built-in tools for achieving the same results.

Custom Python Function for Time Conversion

Before diving into any existing solutions, let’s try solving the problem manually. To convert a given time in seconds into hours, minutes, and seconds, we can break it down into a few logical steps:

1. Handling Large Numbers of Seconds

If the input seconds exceed the number of seconds in a day, we can calculate how much time remains after dividing by the number of seconds in a day:

Code
seconds = seconds % (24 * 3600)

The modulo operation ensures we only work with the time under 24 hours.

2. Extracting Hours

To get the number of hours, we divide the total seconds by the number of seconds in an hour (3600). Using floor division (//) ensures we get the integer part of the quotient:

Code
hours = seconds // 3600

3. Calculating Minutes

After calculating hours, we use the modulo operator again to get the remaining seconds. Then, we repeat the process for minutes by dividing the remaining seconds by 60:

Code
seconds %= 3600
minutes = seconds // 60

4. Getting Seconds

Finally, we apply the modulo operation to find the remaining seconds:

Code
seconds %= 60

Let’s compile all of this into a Python function:

Python
def convert_to_time_format(sec):
    sec = sec % (24 * 3600)  # Restricting to a 24-hour format
    hours = sec // 3600
    sec %= 3600
    minutes = sec // 60
    sec %= 60
    return "{:02d}:{:02d}:{:02d}".format(hours, minutes, sec)

n = 10000
print("Time in hours, minutes, and seconds:", convert_to_time_format(n))

Running the above code will give the following output:

Code
Time in hours, minutes, and seconds: 02:46:40
VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Using Python’s time Module

While writing custom functions enhances understanding, Python’s time module can achieve the same results with fewer lines of code. This module allows you to format time based on an epoch (the starting point, often defined as January 1, 1970).

Here’s how to use the time module to convert seconds into hours, minutes, and seconds:

Python
import time

n = 10000
formatted_time = time.strftime("%H:%M:%S", time.gmtime(n))
print("Time in hours, minutes, and seconds:", formatted_time)

The output will be:

Code
Time in hours, minutes, and seconds: 02:46:40

This method is straightforward, converting the seconds directly into a structured format using Unix time.

Additional Features with the time Module

The time module allows you to display additional information such as the day of the week and the month. For example:

Python
n = 100000000000
formatted_time = time.strftime("Day: %a, Time: %H:%M:%S, Month: %b", time.gmtime(n))
print("Formatted Time:", formatted_time)

Output:

Code
Formatted Time: Day: Wed, Time: 09:46:40, Month: Nov

Using Python’s datetime Module

The datetime module offers another powerful way to work with time. You can use timedelta to convert seconds into a readable format that includes days, hours, minutes, and seconds:

Python
import datetime

n = 10000000
formatted_time = str(datetime.timedelta(seconds=n))
print("Time in days, hours, minutes, and seconds:", formatted_time)

This code will output:

Code
Time in days, hours, minutes, and seconds: 115 days, 17:46:40

Interactive Online Demo Tool

Try out the functions shown above directly in an online environment like Google Colab: Open in Google Colab

Conclusion

In this tutorial, we explored three different methods for converting seconds into a readable time format. First, we built our own function, which gave us a deeper understanding of the process. Then, we explored Python’s built-in time and datetime modules, which offer convenient, ready-made solutions for handling time.

Whether you prefer building custom functions or leveraging Python’s existing libraries, having the flexibility to work with time in various formats is a valuable skill in software development.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren