Python get hours, minutes, and seconds from time interval - python

I have timestamps that are calculated by a given interval. Ex: timestamp being 193894 and interval being 20000. The time is calculated by doing 193894/20000 = 9.6947. 9.6947 being 9 minutes and 0.6947 of a minute in seconds (0.6947 * 60) = 42 s (rounded up) thus the human readable timestamp being 9 min 42 sec.
Is there a Pythonic (assuming there is some library) way of doing this rather than doing a silly math calculation like this for every timestamp?
The reason being is because if timestamp is 1392338 (1 hour 9 min 37 sec) something that yields in the hours range, I want to be able to keep it dynamic.
I am just wondering if there was a better way to do this than the mathematical calculation way.

The linked question can help you actually format timedelta object once you have it, but there are a few tweaks you need to make to get the exact behavior you want
from __future__ import division
from datetime import timedelta
from math import ceil
def get_interval(timestamp, interval):
# Create our timedelta object
td = timedelta(minutes=timestamp/interval)
s = td.total_seconds()
# This point forward is based on http://stackoverflow.com/a/539360/2073595
hours, remainder = divmod(s, 3600)
minutes = remainder // 60
# Use round instead of divmod so that we'll round up when appropriate.
# To always round up, use math.ceil instead of round.
seconds = round(remainder - (minutes * 60))
return "%d hours %d min %d sec" % (hours, minutes, seconds)
if __name__ == "__main__:
print print_interval(1392338, 20000)
print get_interval(193894, 20000)
Output:
1 hours 9 min 37 sec
0 hours 9 min 42 sec

Related

How do I convert integer into a time format

How would I go about converting a float like 3.65 into 4 mins 5 seconds.
I have tried using:
print(datetime.datetime.strptime('3.35','%M%-S'))
However, I get this back:
ValueError: '-' is a bad directive in format '%-M:%-S'
Take a look at the following script, you can figure out how to make it work for days years, etc, this only works if we assume the format is "hours.minutes"
import datetime
# Assuming the 3 represents the hours and the 0.65 the minutes
number = 3.65
# First, we need to split the numbero into its whole decimal part
# and its decimal part
whole_decimal_part = hours = int(number) # 3
decimal_part = number % whole_decimal_part # 0.6499999
# Now, we need to know how many extra hours are in the decimal part
extra_hours = round((decimal_part * 100) / 60) # 1
minutes = round((decimal_part * 100) % 60) # 5
hours += extra_hours # 4
time_str = "%(hours)s:%(minutes)s" % {
"hours": hours,
"minutes": minutes
} # 4:5
final_time = datetime.datetime.strptime(time_str, "%H:%M").time()
print(final_time) # 04:05:00
First, you should complain to whoever is giving you time data expressed like that.
If you need to process minutes and seconds as a standalone value, then the datetime object may not your best choice either.
If you still need to convert "3.65" into a datetime object corresponding to "4-05" you could adjust it to be a valid time representation before passing it to strptime()
m,s = map(int,"3.65".split("."))
m,s = (m+s)//60,s%60
dt = datetime.datetime.strptime(f"{m}-{s}","%M%-S")
Split your time into minute and seconds
If seconds is 60 or more, then add extra minutes (//) ; second is the modulo (%)
t="3.65"
m, s = [int(i) for i in t.split('.')]
if s >= 60:
m += s//60
s = s % 60
print(f'{m} mins {s} seconds') # -> 4 mins 5 seconds
while 65 seconds cannot be parsed correctly so you have to manipulate by yourself to clean the data first before parsing.
NOTE: assuming seconds is not a very very big number which can make minutes>60
import datetime
time= '3.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
minute_offset, seconds = divmod(seconds, 60);
minute = int(split_time[0]) + minute_offset
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S')) #1900-01-01 00:04:05
You can alternatively use .time() on datetime object to extract the time
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S').time()) #00:04:05
A much cleaner and safer solution is (to consider hour as well). Convert everything into seconds and then convert back to hours, minutes, seconds
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return "%d:%02d:%02d" % (hour, min, sec)
time='59.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
new_seconds = minute*60 +65
datetime.datetime.strptime(convert(new_seconds),'%H:%M:%S').time()

Get time difference between two datetime objects as hour, min and sec

I want to get the amount of hours, mins and seconds that have passed between two dates using datetime in python3.
This allows for the duration to be calculated, and makes the amount of hours, mins and seconds that have passed.
Note this has not been fully tested.
Code can also be found on Github here
from datetime import datetime
def calculate_time_duration(start_datetime, end_datetime):
"""
Requires two datetime objects,
returns (hours, minutes, seconds)
"""
seconds = (end_datetime - start_datetime).total_seconds()
minutes = seconds // 60
seconds -= minutes * 60
hours = minutes // 60
minutes -= hours * 60
return hours, minutes, seconds

How to convert float into Hours Minutes Seconds?

I've values in float and I am trying to convert them into Hours:Min:Seconds but I've failed. I've followed the following post:
Converting a float to hh:mm format
For example I've got a value in float format:
time=0.6
result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))
and it gives me the output:
00:36
But actually it should be like "00:00:36". How do I get this?
You can make use of the datetime module:
import datetime
time = 0.6
result = str(datetime.timedelta(minutes=time))
You're not obtaining the hours from anywhere so you'll first need to extract the hours, i.e.:
float_time = 0.6 # in minutes
hours, seconds = divmod(float_time * 60, 3600) # split to hours and seconds
minutes, seconds = divmod(seconds, 60) # split the seconds to minutes and seconds
Then you can deal with formatting, i.e.:
result = "{:02.0f}:{:02.0f}:{:02.0f}".format(hours, minutes, seconds)
# 00:00:36
Divmod function accepts only two parameter hence you get either of the two
Divmod()
So you can try doing this:
time = 0.6
mon, sec = divmod(time, 60)
hr, mon = divmod(mon, 60)
print "%d:%02d:%02d" % (hr, mon, sec)

Subtracting pandas timestamps; absolute value

I have been playing a bit to try to understand pandas timestamps and timedeltas. I like how you can operate with them, but when trying subtraction I found this a bit odd:
now = pd.Timestamp('now')
then = now - pd.to_timedelta('1h')
print (now - then)
print (then - now)
print ((now - then).seconds)
print ((then - now).seconds)
Results in:
0 days 01:00:00
-1 days +23:00:00
3600
82800
a) How should I understand this behavior?
b) Is there a way to have an absolute value of the difference of timestamps, the equivalent to abs()?
The reason for this seemingly strange/buggy behaviour is that the .seconds attribute of a timedelta (for pandas.Timedelta, but this is inherited from standard library's timedelta.timedelta) is very ambigous.
The timedelta is stored in 3 parts: days, seconds, microseconds (https://docs.python.org/2/library/datetime.html#timedelta-objects). So the seconds is the sum of hours, minutes and seconds (in seconds).
So there are 2 'strange' things that can lead to confusion:
When having a negative timedelta, you get -1 days +23:00:00 instead of -01:00:00. This is because only the days part can be negative. So a negative timedelta will always be defined as a negative number of days with adding hours or seconds again to get the correct value. So this gives you the +23h part.
The seconds is the sum of hours, minutes and seconds. So the +23:00:00 we get is equal to 82800 seconds.
Bottomline is, the .seconds attribute of a timedelta does not give you the seconds part neither the total seconds (timedelta converted to seconds). So in practice, I think you should almost never use it.
To obtain the timedelta in seconds, you can use the total_seconds method. If I define the negative difference to diff = then - now:
In [12]: diff
Out[12]: Timedelta('-1 days +23:00:00')
In [13]: diff.seconds
Out[13]: 82800
In [14]: diff.total_seconds()
Out[14]: -3600.0

Calculating difference in seconds between two dates not working above a day

I have a function that accepts a date and returns the difference in time between then and the current time (in seconds). It works fine for everything less than a day. But when I even enter a date that's a year in the future, it still returns a number around 84,000 seconds (there are around 86,400 seconds in a day).
def calc_time(date):
future_date = str(date)
t_now = str(datetime.utcnow())
t1 = datetime.strptime(t_now, "%Y-%m-%d %H:%M:%S.%f")
t2 = datetime.strptime(future_date, "%Y-%m-%d %H:%M:%S.%f")
return ((t2-t1).seconds)
Even when I run it with a parameter whose date is in 2014, i get a number way too low.
Anyone have any insight?
Reading the datetime.timedelta docs.
All arguments are optional and default to 0. Arguments may be ints,
longs, or floats, and may be positive or negative.
Only days, seconds and microseconds are stored internally. Arguments
are converted to those units:
A millisecond is converted to 1000 microseconds. A minute is converted
to 60 seconds. An hour is converted to 3600 seconds. A week is
converted to 7 days. and days, seconds and microseconds are then
normalized so that the representation is unique, with
0 <= microseconds < 1000000 0 <= seconds < 3600*24 (the number of
seconds in one day)
-999999999 <= days <= 999999999
The solution is to use .total_seconds() instead of .seconds
The following code will return you the number of days between the two given dates
$daysremaining = ceil(abs(strtotime($yourdate) - strtotime($currentdate)) / 86400);
and to get the difference in seconds use
$secondsremaining = strtotime($yourdate) - strtotime($currentdate);
upvote if useful
ahh. apparently .seconds will only return the difference of seconds within the range of a day.
.seconds will include both hours and minutes, so i needed to add that to .days*86400 to get total seconds.
thanks for the help, everyone! ;D

Categories