Python Forum
Calculating time difference between times and splitting the HH and MM
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculating time difference between times and splitting the HH and MM
#1
Hi,

Can you help with a time comparrison quesion in Python 3.6?

I want to calculate the hours and minutes between two time and then display the difference,, by "splitting" the hours and minutes into a text string along the lines of "The market opens in HH hours and MM minutes"

The solution seems to start off with putting both times into the same format, so I can subtract one from the other. This will handle the minutes element correctly.

The difficulty is being able to "split" the result into Hours and Minutes, to display the difference into the required text string "The market opens in HH hours and MM minutes" with time.split but this fails with a str error.

If I extract the hour elements and then the minute elements from both times and then compare them, this causes problems with carrying over the minutes.

I have tried to manipulate the output "HH:MM", but have failed.

Any help would be appreciated.

Thank you

Bass

import datetime as datetime

local_time = datetime.datetime.now()

# The Sydney Opening time is 22H00M
# This time is put into a valid time string (via .replace)
# in order to subtract the number of hours and minutes until the
# market opens in this line of code: countdown = sydney_open - local_time
# This calculates the correct difference in hours/minutes. But prevents me
# from splitting the result into hours and then minutes.
# One alternative could be to multiply the hours by 60 and adding the 
# minutes element, for both times (current and opening time), then
# calculating the hours by dividing by 60 and then deriving the
# minutes to provide a result in hours and minutes. But this is
# converluted - so looking for a smarter method.

sydney_open = datetime.datetime.strptime('22:00:00', "%H:%M:%S")
sydney_open = local_time.replace(hour=sydney_open.time().hour, minute=0, second=0, microsecond=0)

countdown = sydney_open - local_time

print("local_time = ", local_time)
print("sydney_open  = ", sydney_open)
print("Countdown....", countdown) 

# I want to display the countdown as "The Market opens in HH hours and MM minutes 
# Currently the output is: Sydney opens in 2:04:34.950393
# The preferred output is "Sydney opens in 2 hours and 4 minutes"

"The good thing about standards is that you have so many to choose from" Andy S. Tanenbaum
Reply
#2
take a look at: http://pleac.sourceforge.net/pleac_pytho...times.html
Reply
#3
Thanks Larz60,

I did look at this and the other two links that you (I think it was you?) posted before, but didn't spot a solution. BUT I have been working on this for most of the day so probably missed it.

I'll look at it with fresh eyes!

Appreciate your help.

Bass

"The good thing about standards is that you have so many to choose from" Andy S. Tanenbaum
Reply
#4
It seems to be calculating correctly. If the only problem is getting the hours and minutes into a string, you can calculate that from the seconds attribute of the timedelta object:

hours = countdown.seconds // 3600
minutes = (countdown.seconds // 60) % 60
print('The market opens in {} hours and {} minutes.'.format(hours, minutes))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thanks Guys,

It's now working.

Appreciate your help.

Bass

"The good thing about standards is that you have so many to choose from" Andy S. Tanenbaum
Reply
#6
pendulum is what i think is best date/times library for Python.
All python standard library datetime work in pendulum.
So as a example can use sydney_open made in datetime and subtract if from pendulum.now().
>>> import pendulum

>>> now = pendulum.now()
>>> now
<Pendulum [2017-07-03T00:56:43.582239+02:00]>
>>> countdown = sydney_open - now

>>> print(f"Sydney opens in {countdown.hours} hours and {countdown.minutes} minutes")
Sydney opens in 21 hours and 3 minutes
Reply
#7
(Jul-02-2017, 10:04 PM)ichabod801 Wrote: It seems to be calculating correctly. If the only problem is getting the hours and minutes into a string, you can calculate that from the seconds attribute of the timedelta object:

hours = countdown.seconds // 3600
minutes = (countdown.seconds // 60) % 60
print('The market opens in {} hours and {} minutes.'.format(hours, minutes))

Alternate way.

from collections import namedtuple
def to_hms(seconds):
   st_time = namedtuple('time', 'hours minutes seconds')
   minutes, seconds = divmod(seconds, 60)
   hours, minutes = divmod(minutes, 60)
   return st_time(hours, minutes, seconds)

countdown = to_hms(3660)
print(f"Sydney opens in {countdown.hours} hours and {countdown.minutes} minutes")
Output:
Sydney opens in 1 hours and 1 minutes
Btw: namedtuple is underused. But the interesting part is divmod.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#8
Thanks for all the additional help.

This is all useful advice for my routine. Sydney opening on a Sunday evening is significant as it opens the global currency market (which is closed Friday evening until Sunday evening). The market becomes more active/volatile as each trading day open across the world opens/closes, and therefore I can use the coutdown throught the day to provide alerts for say New York (which is perhaps the most volatile, followed by London).

Pendulum looks like a useful module, especially as it is designed, using both the standard tools available for the datetime modules as well as additional features. So hopefully is/will become a sort of  "one stop shop" for date and time manipulation. Thanks snippsat

Let me know if anyone else is using Python with FX, happy to share solutions for API's and  FX analysis.

Thank you for all your help, much appreciated.

Bass
PS Starting to try and use tags etc. but hey learning is all about making mistakes, like highlighting whole paragraphs!

"The good thing about standards is that you have so many to choose from" Andy S. Tanenbaum
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  time difference bettwenn logs enkliy 14 875 Nov-21-2023, 04:51 PM
Last Post: rob101
  Hard time trying to figure out the difference between two strings carecavoador 2 644 Aug-16-2023, 04:53 PM
Last Post: carecavoador
  Sum up Time difference tester_V 10 2,356 Apr-06-2023, 06:54 AM
Last Post: Gribouillis
  splitting total time between days tester_V 7 2,966 Nov-14-2020, 04:40 AM
Last Post: tester_V
  How to get indices of minimum time difference Mekala 1 2,114 Nov-10-2020, 11:09 PM
Last Post: deanhystad
  Split gps files based on time (text splitting) dervast 0 1,851 Nov-09-2020, 09:19 AM
Last Post: dervast
  How to calculate time difference between each row of dataframe in seconds Mekala 1 2,516 Jul-16-2020, 12:57 PM
Last Post: Larz60+
  Correlation of Incidents using time difference Rajhesh 1 1,778 Jun-27-2019, 03:44 PM
Last Post: Larz60+
  Time Difference in Epoch Microseconds then convert to human readable firesh 4 11,543 Feb-27-2018, 09:08 AM
Last Post: firesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020