PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python Convert Seconds To hh:mm:ss (Hours, Minutes, and Seconds)

Python Convert Seconds To hh:mm:ss (Hours, Minutes, and Seconds)

Updated on: February 17, 2022 | Leave a Comment

There are cases where the application gets time information in seconds, but we need to store that information in hours, minutes, seconds (hh:mm:ss) format, or vice-versa.

By the end of this article, you’ll learn: –

  • How to convert seconds into hours, minutes, seconds (hh:mm:ss) format
  • How to convert hours, minutes, seconds (hh:mm:ss) to seconds.

How to Convert Seconds To Hours, Minutes, and Seconds using Timedelta

The below steps show how to convert seconds to hh:mm:ss format in Python using the timedelta class.

  1. Import the datetime module

    Python’s datetime module provides functions that handle many complex functionalities involving the date and time. Import it using a import datetime statement.

  2. Use the timedelta class of a datetime module

    The A timedelta represents a duration in days, hours, minutes, and seconds. Use the timedelta() constructor and pass the seconds value to it using the seconds argument.

    The timedelta constructor creates the timedelta object, representing time in days, hours, minutes, and seconds (days, hh:mm:ss.ms) format.

    For example, datetime.timedelta(seconds=6010) will return 1 hour 40 minutes 10 seconds.

Example 1: Convert seconds to hh:mm:ss

from datetime import timedelta

sec = 6010
print('Time in Seconds:', sec)

td = timedelta(seconds=sec)
print('Time in hh:mm:ss:', td)

# Use the below code if you want it in a string
print(str(timedelta(seconds=sec)))

Output:

Time in Seconds: 6010
Time in hh:mm:ss: 1:40:10

Example 2: Display it in Human readable format

  • First, Create the timedelta object by passing seconds to it
  • Next, convert the timedelta object to a string
  • Next, split the string into individual components to get hours, minutes, and seconds
from datetime import timedelta

def get_time_hh_mm_ss(sec):
    # create timedelta and convert it into string
    td_str = str(timedelta(seconds=sec))
    print('Time in seconds:', sec)

    # split string into individual component
    x = td_str.split(':')
    print('Time in hh:mm:ss:', x[0], 'Hours', x[1], 'Minutes', x[2], 'Seconds')

get_time_hh_mm_ss(29500)
get_time_hh_mm_ss(7500040)

Output:

Time in seconds: 29500
Time in hh:mm:ss: 8 Hours 11 Minutes 40 Seconds

Time in seconds: 7500040
Time in hh:mm:ss: 86 days, 19 Hours 20 Minutes 40 Seconds

Use Python built-in function divmod() function if you don’t want to include days:

The divmod() function Take two numbers as arguments and return a pair of numbers consisting of their quotient and remainder.

seconds = 7500040
print('Time in Seconds:', seconds)

# get min and seconds first
mm, ss = divmod(seconds, 60)
# Get hours
hh, mm= divmod(mm, 60)

print('Time in Seconds:', hh, 'Hours', mm, 'Minutes', ss, 'Seconds')

Output:

Time in Seconds: 7500040
Time in Seconds: 2083 Hours 20 Minutes 40 Seconds

Convert hh:mm:ss to Seconds

Now, let’s assume we have to inverse the above example, i.e., we want to convert hours, minutes, and seconds time string to seconds in Python.

Let’s assume you have a string in the format H:MM:SS, and you need the represent it in seconds.

For example:

  • “1:40:10” would produce an output of 6010 seconds
  • “0:05:15” would produce an output of 315 seconds
  • “0:00:32” would produce an output of 32 seconds

Steps to convert hours, minutes, seconds to seconds:

  • Split the string into individual components and store it in the hours, minutes, and seconds variable.
  • Multiply hours by 3600
  • Multiple minutes by 60
  • Add all the numbers to the seconds variable.

Example:

def get_seconds(time_str):
    print('Time in hh:mm:ss:', time_str)
    # split in hh, mm, ss
    hh, mm, ss = time_str.split(':')
    return int(hh) * 3600 + int(mm) * 60 + int(ss)

print('Time in Seconds:', get_seconds('1:40:10'))
print('Time in Seconds:', get_seconds('0:05:15'))
print('Time in Seconds:', get_seconds('0:00:32'))

Output:

Time in hh:mm:ss: 1:40:10
Time in Seconds: 6010

Time in hh:mm:ss: 0:05:15
Time in Seconds: 315

Time in hh:mm:ss: 0:00:32
Time in Seconds: 32

Convert Current Time in Seconds to Days, hh:mm:ss

  • Get the current time in seconds using the timestamp() function
  • Pass it to the timedelta() constructor
from datetime import datetime, timedelta

# current time in seconds
sec = datetime.now().timestamp()
print('Time in seconds:', sec)

# convert to Days, hh:mm:ss
td = timedelta(seconds=sec)
print('Time in Days, hh:mm:ss.ms:', td)

Output:

Time in seconds: 1626698950.164824
Time in Days, hh:mm:ss.ms: 18827 days, 12:49:10.164824

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com