DEV Community

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

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


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.


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()))

The program shows the current date and time:

Thu Feb 13 14:00:03 2020


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()))


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)


This returns the nicely formatted time:

$ python

Related links:

Top comments (0)