Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Seconds to datetime timedelta [duplicate]

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to this format in Python?

like image 930
Specto Avatar asked Apr 21 '09 23:04

Specto


People also ask

How to convert a timedelta to seconds in Python?

To convert a timedelta to seconds in Python, we can use the total_seconds()function on a timedelta object. import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,7,0,0,0) timedelta_object = datetime2 - datetime1 print(timedelta_object.total_seconds()) #Output: 172800.0

How to get the number of minutes in a timedelta?

To get the actual number of minutes, you'd actually start with the seconds (that are accessible directly on the timedelta object): Jenn is a new contributor. Be nice, and check out our Code of Conduct .

What is datetime timedelta in pandas?

Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.seconds property in pandas.Timedelta is used to return Number of seconds. Attention geek!

How to convert datetime to seconds in Python?

Use the timestamp () method. If your Python version is greater than 3.3 then another way is to use the timestamp () method of a datetime class to convert datetime to seconds. This method returns a float value representing even fractions of a second.


6 Answers

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
like image 80
SilentGhost Avatar answered Sep 24 '22 05:09

SilentGhost


By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

And then use string formatting to convert the result into your desired output:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
like image 44
Brandon Rhodes Avatar answered Sep 25 '22 05:09

Brandon Rhodes


I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59

like image 35
anatoly techtonik Avatar answered Sep 24 '22 05:09

anatoly techtonik


Using datetime:

With the ':0>8' format:

from datetime import timedelta

"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Without the ':0>8' format:

"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Using time:

from time import gmtime
from time import strftime

# NOTE: The following resets if it goes over 23:59:59!

strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'

strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'

strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'

strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
like image 45
marcell Avatar answered Sep 25 '22 05:09

marcell


This is my quick trick:

from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'

For more info Visit: https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_timespan

like image 28
doories Avatar answered Sep 24 '22 05:09

doories


The following set worked for me.

def sec_to_hours(seconds):
    a=str(seconds//3600)
    b=str((seconds%3600)//60)
    c=str((seconds%3600)%60)
    d=["{} hours {} mins {} seconds".format(a, b, c)]
    return d


print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']

print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
like image 28
naive decoder Avatar answered Sep 23 '22 05:09

naive decoder