How to convert time seconds to h:m:s format in Python?



In this article, we will discuss various ways to convert time in seconds to H M S format in python. H M S format means Hours: Minutes: Seconds.

Using arithmetic operations (Naïve method)

In this method, we use mathematic calculations to convert time in seconds to h m s format. Here we take the input from the user in seconds and convert it into the required format.

Example

In this example, we convert a time in seconds to h m s format.

seconds = int(input("Enter the number of seconds:")) seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 print("%d:%02d:%02d" % (hour, minutes, seconds))

Output

The output of the code is as follows.

Enter the number of seconds:5000000
20:53:20

Using timedelta() method

In this method, we use the .timedelta() method to convert a time in seconds to h m s format. The .timedelta() method is provided by the datetime library which is generally used to calculate the difference between given dates. We also this method for manipulating dates in python.

Syntax

The syntax of the timedelta() method is as follows.

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Here only send the seconds parameter as we need to convert time in seconds to h m s format.

Example

The following is an example code to convert time in seconds to H M S format.

import datetime timedelta_obj = datetime.timedelta(seconds=7896354) print("Time in H M S format: ",timedelta_obj)

Output

The output of the above code is as follows.

Time in H M S format:  91 days, 9:25:54

Using .strftime() method

The strftime() method is provided by the datetime module in python. Here we use the strftime() method to convert a string datetime to datetime. It is also used to convert datetime to epoch.

Epoch is the starting point of time and is platform-dependent. The epoch is January 1, 1970, 00:00:00 (UTC) on Windows and most Unix systems, and leap seconds are not included in the time in seconds since the epoch. We use time.gmtime(0) to get the epoch on a given platform.

Syntax

The syntax of the strftime() method is given below.

date.strftime(format)

Where, format is used to specify the required format of the output.

Here, we want to convert time in seconds to H: M:S format. So the format code, in this case, is “%H:%M:%S”.

Example

Following is an example code to convert time in seconds to H:M:S format in python by using the .strftime() method.

import time seconds = 123455 time_obj = time.gmtime(seconds) resultant_time = time.strftime("%H:%M:%S",time_obj) print("Time in H M S format",resultant_time)

Output

The following is the output for the above code.

Time in H M S format 10:17:35

Advertisements