I have a TimeField() in my django models. I want to convert the sum of the record of this to hours.
Here's the actual code in my view:
hours_week_decimal = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).aggregate(total=Sum('working_hour')) # this method return a dict of decimal
total_hours_week = convertDecimalToHours(hours_week_decimal)
and the related function:
def convertDecimalToHours(times):
total_time = 0
for k, v in times.items():
total_time += int(v)
print("type: {} - value: {}".format(type(total_time), total_time))
This returned me:
type: int - value: 166000
I have two hours:
Monday (08:30) and Tuesday(08:30)
It must have returned me "17:00"
Hope you can help me in solving this problem :)
The problem is that 30m+30m = 60m that yes, is 1h, but you expected that the calculator was able to understand that you want 30+30 = 1h
So, in your case, you have to explicit convert 8:30 to 8.5
A fast but not graceful approach to extend your example with few lines can be:
Convert your ints to strings.
Cut out the hours (positions 0 and 1) and multiply for 60 to obtain minutes.
Sum this result to the minutes (positions 2 and 3)
After doing this for every TimeField you have, sum all your times converted in minutes and then reconvert in hours.
In your example:
def convertDecimalToHours(times):
total_time = 0
for k, v in times.items():
tmp_time = str(int(v))
minutes = int(tmp_time[2:4]) + int(tmp_time[0:2])*60
total_time += minutes / 60 # Now your 8:30 is 8.5
print("type: {} - value: {}".format(type(total_time), total_time))
Your output here will be 17.
I suggest you to use this as example to understand the concept, not as a packed solution to your problem.
thanks for your answer,
In my database, i have a column of type "Time". The value's stored like this: 08:30:00.000000.
with my previous code, the times variables (passed in parameters) are like that:
{'total': Decimal('166000.000000')}
Related
Ive written this code and ive obtained the desired output however it is not in the correct format. Essentially the codewars challenge was to take a number of seconds up to around 350000 and then split it into hours then minutes then seconds. For example my code would take x seconds then express it as y:z:p (where y, z and p represent single digit integers) however i would like my code to express it as 0y:0z:0p unless y,z or p are already two digit integers.
Here is my code:
secs = 350000
mins = secs/60
hrs = mins/60
hrs_hol = int(hrs)
print(hrs_hol, hrs)
hrs_rem = hrs-hrs_hol
print(hrs_rem)
mins_from_hrs_rem = hrs_rem*60
mins_hol = int(mins_from_hrs_rem)
mins_rem = mins_from_hrs_rem - mins_hol
secs_from_min_rem = mins_rem*60
secs_final = int(secs_from_min_rem)
H = str(hrs_hol)
M = str(mins_hol)
S = str(secs_final)
print(H+':'+M+':'+S)
Thankyou!
Try this:
H = str(hrs_hol).zfill(2)
M = str(mins_hol).zfill(2)
S = str(secs_final).zfill(2)
Remove the assignments to H, M & S then:
print(f'{hrs_hol:02d}:{mins_hol:02d}:{secs_final:02d}')
Here we use an f-string and a format specifier that indicates a minimum of two digits (left-padded with zero if necessary)
I am asked to do this:
Write a program that adds one second to a clock time, given its hours, minutes and seconds.
Input consists of three natural numbers h, m and s that represent a clock time, that is, such that h<24, m<60 and s<60.
This is the code I came up with:
from easyinput import read
h = read(int)
m = read(int)
s = read(int)
seconds = (s+1)%60
minutes = (m + (s+1)//60)%60
hours = h + (m + (s+1)//60))//60
print(hours, minutes, seconds)
It does its function well, if I have
13 59 59
it returns
14 0 0
I am sure it could be bettered, but that's not the problem right now.
The problem is that I need the format to be like this:
11:33:16
It should be “HH:MM:SS”, and I don't know how to do it.
Anyone could help me?? Thanksss :)))
Use an f-string with format modifiers. 02d says "an int with field width 2 padded with 0."
print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
>>> hours = 13
>>> minutes = 3
>>> seconds = 5
>>> print(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
13:03:05
>>>
Note that the d in the format specifiers is unnecessary. You could write:
print(f"{hours:02}:{minutes:02}:{seconds:02}")
Documentation on f-strings.
Usually, you don't want to deal with calculating date and time yourself, so a better approach is to use the native library that works with date and time out of the box:
from datetime import datetime, timedelta
from easyinput import read
h, m, s = read(int), read(int), read(int)
time = datetime.now().replace(hour=h, minute=m, second=s)
time += timedelta(seconds=1)
print(time.strftime("%H:%M:%S"))
print(f'{hours:>02}:{minutes:>02}:{seconds:>02}')
Is it possible to convert int into hours:min:sec
import datetime
x = 40000
t = int(x)
day = t//86400
hour = (t-(day*86400))//3600
min = (t - ((day*86400) + (hour*3600)))//60
seconds = t - ((day*86400) + (hour*3600) + (min*60))
hello= datetime.time(hour.hour, min.minute, seconds.second)
print (hello )
I want this Output:- 11:06:40
You can also outsource all the division and modulo operations to Python built-ins (remember: batteries are included!)
>>> import time
>>> x = 40000
>>> time.strftime('%H:%M:%S', time.gmtime(x))
'11:06:40' # <- that's your desired output
>>> time.gmtime(x)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=6, tm_sec=40, tm_wday=3, tm_yday=1, tm_isdst=0)
>>> time.gmtime(x).tm_hour # <- that's how to access individual values
11
You almost got it.
hour, min and seconds are integers, and integers don't have hour, minute or second attributes.
Change
hello = datetime.time(hour.hour, min.minute, seconds.second)
to
hello = datetime.time(hour, min, seconds)
As a side note, t = int(x) is totally unnecessary as x is already an int.
As a side note 2, in the future please provide the error you receive.
Note: In response to #Pavel's answer,
You may find time.gmtime(x) not giving the right time as shown on your pc.
To produce a time consistent with what is on your pc, use time.localtime(x) instead
I need help converting this into an hour and minute format using the remainder operator. I'm relatively new to python and coding in general, so help is greatly appreciated.
#Define the value of our variables
numberOfEpisodes = 13
minutesPerEpisode = 42
#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//minutesPerHour
#Display the output
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.') print('This is equivalent to', equivalency)
This is what I currently have, I am able to obtain the amount of hours there are, but I can't figure out how to adjust the code to include the remaining minutes.
Sorry if I don't make a whole lot of sense, but hopefully you'll understand.
You can use // integer division and % modulus for remainder. (You can read more about Python's int and float division here)
>>> numberOfEpisodes = 13
>>> minutesPerEpisode = 42
>>> totalMinutes = numberOfEpisodes * minutesPerEpisode
>>> totalMinutes
546
>>> minutesPerHour = 60
>>> totalHours = totalMinutes // minutesPerHour
>>> totalHours
9
>>> remainingMinutes = totalMinutes % minutesPerHour
>>> remainingMinutes
6
Result
>>> print('{} episodes will take {}h {}m to watch.'.format(numberOfEpisodes,totalHours, remainingMinutes))
13 episodes will take 9h 6m to watch.
Use the modulo operator %
#Define the value of our variables
numberOfEpisodes = 13
minutesPerEpisode = 42
#Calculate the results
totalMinutes = numberOfEpisodes * minutesPerEpisode
equivalency=totalMinutes//60
minutes= totalMinutes%60
#Display the output
print(numberOfEpisodes, 'episodes will take', totalMinutes, 'minutes to watch.')
print('This is equivalent to', equivalency,minutes)
Check out the timedelta documentation in the datetime module documents. You can create the durations as time deltas in minutes, and then when you want to display it you can ask timedelta to give it in whatever format you want. You could use arithmetic calculations to get the hours and minutes, but if you then need to use this data to calculate dates and times, for example to know at what time the show will be over if it starts at 09:00, you will have many extra steps to go through, instead of just using the timedelta.
I have a function, getHoursSince():
def getHoursSince (date):
prior = datetime.datetime.now() - datetime.timedelta(days=date)
priorHour = prior.hour
hoursSinceDate = ...
return hoursSinceDate
so, I can get a date object, given a constant value, i.e. if yesterday = 1, I can call getHoursSince(yesterday). What I don't know how to do is to get the number of hours between datetime.datetime.now() and the priorHour variable -- any ideas?
You are going about it the wrong way; you just convert the timedelta() to hours:
def getHoursSince(date):
return int(datetime.timedelta(days=date).total_seconds() // 3600)
which gives:
>>> getHoursSince(1)
24
>>> getHoursSince(1.5)
36
>>> getHoursSince(2)
48
>>> getHoursSince(3)
72
but you can just as well base that off of simple arithmetic:
def getHoursSince(date):
return int(24 * date)
The timedelta.total_seconds() documentation says:
For interval units other than seconds, use the division form directly
(e.g. td / timedelta(microseconds=1)).
Here's what that would look like in this case:
def getHoursSince(date):
return datetime.timedelta(days=date) // datetime.timedelta(hours=1)