Jan-21-2022, 10:55 AM
I’m trying to write a dynamic script which takes in various hours/minutes as input data and then formats the output to
I figure to achieve this I can leverage the built-in
The end goal is to be able to add, subtract, compare, and reformat all kinds of different time input using various class methods. The unit test processes a hundred or so different assertions. But for now I am breaking down this larger task down to basic, bite-size smaller steps. For example, I’m focussing on just the first four unit test assertions (copied at the very bottom of this post). I am also not even bothering with classes or even functions (for now) and instead just focusing on the raw calculations and logic.
Here is one script I came up with:
The output here of all five print statements is wrong.
The timedelta output assigned to the
The second print statement shows the numbers as floats, which is also not what I want.
With the third print statement, when I convert the float results to integers, the significant digits are off. I need
In the fourth line of output, I am getting closer to the desired end result by converting the
In the final line of output, it’s formatted exactly as I need it by adding
So in this one specific unit test where the two variables entered are
When I first encountered this exercise, I immediately went to the
I found a Stack Overflow question on converting date time and deltas to hours and minutes which has a lot of answers that demonstrate many different ways to do this.
I found a similar SO question with answers demonstrating the same task by performing basic arithmetic operations using moduli and floor division which I leveraged for my script above.
Based on a SO question on converting seconds to string formatting, I played around some more with datetime and strftime with a fresh script:
I tried this next:
At this point I am stabbing in the dark.
What I need is a way to get:
This is for non-accredited self-study online courseware. I’ve put in enough effort that I feel I am ready to see a solution, at least for these four output scenarios.
Hour:Minute
. I figure to achieve this I can leverage the built-in
.strftime("%H:%M"))
method as well as leverage the timedelta
method form the datetime
module.The end goal is to be able to add, subtract, compare, and reformat all kinds of different time input using various class methods. The unit test processes a hundred or so different assertions. But for now I am breaking down this larger task down to basic, bite-size smaller steps. For example, I’m focussing on just the first four unit test assertions (copied at the very bottom of this post). I am also not even bothering with classes or even functions (for now) and instead just focusing on the raw calculations and logic.
Here is one script I came up with:
import datetime duration = datetime.timedelta(hours=8, minutes=0) print(duration) totsec = duration.total_seconds() h = totsec//3600 m = (totsec%3600) // 60 sec = (totsec%3600)%60 #just for reference print(f"{h}:{m}") print(f"{int(h)}:{int(m)}") print(str(duration)[:-3])As you can see above, where I invoke the timedelta method, two variables are 8 hours and 0 minutes. The unit test expects this output:
08:00
. When I run my script, I get this output:Quote:$ python clock.py
8:00:00
8.0:0.0
8:0
8:00
08:00
The output here of all five print statements is wrong.
The timedelta output assigned to the
duration
variable shows seconds but the task I am working on expects hours and minutes to show and not seconds.The second print statement shows the numbers as floats, which is also not what I want.
With the third print statement, when I convert the float results to integers, the significant digits are off. I need
08
to show and not just 8
.In the fourth line of output, I am getting closer to the desired end result by converting the
duration
to a string and then slicing off the trailing 3 characters. But the hour output needs to be 2 digits and right now it is only 1 digit.In the final line of output, it’s formatted exactly as I need it by adding
0
to the string.So in this one specific unit test where the two variables entered are
8
and 0
, it would pass. But because I have micromanaged all the variables, it’s not dynamic. Like, in the next unit test, when 11
is entered as the hour value, the output would be: 011:00
which is not what I want. There obviously has got to be a more dynamic, flexible and Pythonic solution.When I first encountered this exercise, I immediately went to the
.strftime("%H:%M"))
method but as soon as I combined it with timedelta()
, I quickly learned that timedelta()
doesn’t support strftime()
. They just aren’t compatible. That’s what someone clarified on reddit:Quote:Subtracting two datetimes gives you a timedelta object, not a datetime. timedelta objects are really just a number of seconds, they're not real "dates", so they can't be formatted with strftime.Source link.
I found a Stack Overflow question on converting date time and deltas to hours and minutes which has a lot of answers that demonstrate many different ways to do this.
I found a similar SO question with answers demonstrating the same task by performing basic arithmetic operations using moduli and floor division which I leveraged for my script above.
Based on a SO question on converting seconds to string formatting, I played around some more with datetime and strftime with a fresh script:
import datetime duration = int(datetime.timedelta(hours=8,minutes=0).total_seconds().strftime("%H:%M")) print(duration)...which produced this output:
Quote:› python clock_func3.py
Traceback (most recent call last):
File "/home/gnull/dev/projects/python/2018-and-2020/exercism-v3/python/clock/clock_func3.py", line 3, in <module>
duration = int(datetime.timedelta(hours=8,minutes=0).total_seconds().strftime("%H:%M"))
AttributeError: 'float' object has no attribute 'strftime'
I tried this next:
import datetime duration = int(datetime.datetime(year=0,month=0,day=0,hour=8,minute=0).total_seconds().strftime("%H:%M")) print(duration)...which produces this output:
Quote:$ python clock_func3.py
Traceback (most recent call last):
File "/home/gnull/dev/projects/python/2018-and-2020/exercism-v3/python/clock/clock_func3.py", line 3, in <module>
duration = int(datetime.datetime(year=0,month=0,day=0,hour=8,minute=0).total_seconds().strftime("%H:%M"))
ValueError: year 0 is out of range
At this point I am stabbing in the dark.
What I need is a way to get:
- “08:00” as output when 8 hours and 0 minutes are the entered input.
- “00:00” as output when 24 hours and 0 minutes are entered
- “01:00” as output when 25 hours and 0 minutes are entered
- “04:00” as output when 100 hours and 0 minutes are entered
This is for non-accredited self-study online courseware. I’ve put in enough effort that I feel I am ready to see a solution, at least for these four output scenarios.