DEV Community

Cover image for Convert seconds to day, hour, minutes and seconds in Python
bluepaperbirds
bluepaperbirds

Posted on

Convert seconds to day, hour, minutes and seconds in Python

In Python, the time module provides many time related functions.

You can use the time module to get the time and date and other things. You can use the function time.time() to get get the current time

import time

time.time()

But if you output it with the print function, it doesn't show in human readable format. Instead you get a number called the epoch or Unix time.

unix time

This is a system for describing a point in time that is used by computers. So how do you convert it to time?

Before playing with time module, you should know the basics of Python.

ctime

One way to solve this is by calling the function ctime(). The ctime() function converts a time (seconds since the epoch) to a string of a form: 'Sun Jun 20 23:21:05 1993'.

import time

now = time.ctime(int(time.time()))
print(now)

The program shows the current date and time:

Thu Feb 13 14:00:03 2020

strftime

To get just the time you can use the function strftime(). This outputs hours "%H" and minutes "%M". To get the seconds you can use "%S". Try the code:

import time

now = time.strftime("%H:%M", time.localtime(time.time()))
print(now)

alternative

To convert the time manually to hours, seconds and minutes you can do the math manually. Then use f-strings to output 2 digits for every variable:

import time

time = time.time()
time = time % (24 * 3600)
hour = round(time // 3600)
time %= 3600
minutes = round(time // 60)
time %= 60
seconds = round(time)

print(f"{hour:02d}:{minutes:02d}:{seconds:02d}")

This returns the nicely formatted time:

$ python example.py
13:06:29

Related links:

Top comments (0)