Convert float to float time in python - python

How in python code convert 10.5 to 10:30 (10 hours and 30 minutes).
Now time = 10.5 I need result time = 10:30
Any simple solution?
Tnx all for help

Try this:
time = 10.5
print '{0:02.0f}:{1:02.0f}'.format(*divmod(float(time) * 60, 60))
10:30

Split the number into its integer and decimal parts, then multiply the decimal part with 60 and put them back together:
t = 10.5
hour, minute = divmod(t, 1)
minute *= 60
result = '{}:{}'.format(int(hour), int(minute))
# result: 10:30
See also the documentation for the divmod function and this question for other ways to split a float into two parts.

You can pass the raw float value as hours to datetime.timedelta(), and then operate with it in what I think is the most comfortable way:
from datetime import datetime, timedelta
td = timedelta(hours=10.5)
dt = datetime.min + td
print("{:%H:%M}".format(dt))
print(td.total_seconds())

Related

Dealing with time format greater than 24 hours

I have data of experiments with time greater than 24 hours. For ex. [23:24:44, 25:10:44]. To operate duration of tests, I like to use Python, however I have a value error when I create datetime.time() with hours more than 23:59:.
You could split your time by the colons in order to get a list of the component parts, which you could then use to initialise your timedelta:
from datetime import timedelta
myDuration = "25:43:12"
mD = [int(x) for x in myDuration.split(":")]
delta = timedelta(hours=mD[0], minutes=mD[1], seconds=mD[2])
print(delta)
# 1 day, 1:43:12

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

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)

Python convert timedeltas into hours in string format

I have a timedelta object which is 3457 hours
timedelta(hours=3457)
I want to represent it in "HH:MM" format, which is "3457:00"
I do:
from datetime import datetime
hours = timedelta(hours=3457)
hours_string = time.strftime("%H:%M", time.gmtime(hours.seconds))
print hours_string
"01:00"
How can I get "3457:00"?
Please note that 3457:00 is a nonsensical format. The "hour-colon-minutes" format is used in dates and times, and the hour then can't reasonably be any higher than 23. A more reasonable format is: 3457h 0m.
You can get it like this:
from datetime import timedelta
delta = timedelta(hours=3457)
minutes, seconds = divmod(delta.seconds, 60)
hours, minutes = divmod(minutes, 60)
hours += delta.days * 24
print '%sh %sm' % (hours, minutes)
Of course, an easier way is this:
from datetime import timedelta
delta = timedelta(hours=3457)
print delta
But that will give you "144 days, 1:00:00", which is a sane format, but not what you want.
As the timedelta documentation notes, only days, seconds and microseconds are stored internally -- which means you'll have to manually convert them to the units you want (hours and minutes). Here's one way to do that:
from datetime import timedelta
d = timedelta(hours=3457, minutes=42)
wholehours, seconds = divmod(d.seconds, 60*60)
wholeminutes = seconds//60
deltahours = d.days*24 + wholehours
print('{:d}:{:02d}'.format(deltahours, wholeminutes))
# 3457:42
Here's a simpler alternative that produces the same result:
def deltatime_hours_mins(dt, sep=':'):
secs = int(dt.total_seconds())
return '{:d}{}{:02d}'.format(secs//3600, sep, secs//60 % 60)
print(deltatime_hours_mins(d))

how to calculate timedelta python

What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for ease:
from datetime import datetime
dt = datetime.strptime( date, '%Y-%m-%d %H:%M' )
dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 )
Unfortunately, even after reading the documentation I still do not understand how that line works.
What is the timedelta line doing? How does it work?
Additionally, before I found this stackoverflow post, I was working with time.struct_time tuples. I had a variable tm:
tm = time.strptime(...)
I was simply accessing the hour through tm.tm_hour and subtracting seven from it but this, for obvious reasons, does not work. This is why I am now trying to use datetime. tm now has the value
tm = datetime.strptime(...)
I'm assuming using datetime is the best way to subtract seven hours?
Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this?
What is the timedelta line doing? How does it work?
It creates a timedelta object.
There are two meanings of "time".
"Point in Time" (i.e, date or datetime)
"Duration" or interval or "time delta"
A time delta is an interval, a duration, a span of time. You provided 3 values.
0 days.
2*60*60 + 30*60 seconds.
timedelta() generates an object representing an amount of timeā€”the Greek letter delta is used in math to represent "difference". So to compute an addition or a subtraction of an amount of time, you take the starting time and add the change, or delta, that you want.
The specific call you've quoted is for generating the timedelta for 2.5 hours. The first parameter is days, and the second is seconds, so you have (0 days, 2.5 hours), and 2.5 hours in seconds is (2 hours * 60 minutes/hour * 60 seconds/minute) + (30 minutes * 60 seconds / minute).
For your case, you have a negative time delta of 0 days, 7 hours, so you'd write:
timedelta(0, -7 * 60 * 60)
... or timedelta(0, -7 * 3600) or whatever makes it clear to you what you're doing.
Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this?
Yes there is: datetime has built-in timezone conversion capabilities. If you get your datetime object using something like this:
tm = datetime.strptime(date_string, '%Y-%m-%d %H:%M')
it will not have any particular timezone "attached" to it at first, but you can give it a timezone using
tm_utc = tm.replace(tzinfo=pytz.UTC)
Then you can convert it to US/Pacific with
tm_pacific = tm_utc.astimezone(pytz.all_timezones('US/Pacific'))
I'd suggest doing this instead of subtracting seven hours manually because it makes it clear that you're keeping the actual time the same, just converting it to a different timezone, whereas if you manually subtracted seven hours, it looks more like you're actually trying to get a time seven hours in the past. Besides, the timezone conversion properly handles oddities like daylight savings time.
To do this you will need to install the pytz package, which is not included in the Python standard library.

Categories