440,715 Members | 768 Online Need help? Post your question and get tips & solutions from a community of 440,715 IT Pros & Developers. It's quick & easy.

# how to find a time between the two given time

 P: 2 hello , i need a help regarding python programming: basically i need to find out times between the start and the stop time. Here is what i have tried--- Expand|Select|Wrap|Line Numbers s = raw_input('enter first time (hh:mm:ss ):') z = raw_input('enter the second time (hh:mm:ss):') if ':' in s:  h, m, ss = s.split(':')  q = int(h)*3600 + float(m)* 60 + float(ss)   if ':' in z:  hh, mm, sss = z.split(':')  p = int(hh)*3600 + float(mm)* 60 + float(sss) Now here i have taken out the value of q and p . Now how do i take a variable "tm" and compare the time as ` q <= tm <= p` and then use the variable tm in my other processing Mar 24 '11 #1
3 Replies

 Expert Mod 2.5K+ P: 2,851 You can use the time module for date and time math. time.strptime returns a struct_time object by parsing a string representing a time according to a format. time.localtime() returns a struct_time object representing the current time. A struct_time object is iterable as a tuple, so a given time and current time can be combined by slicing. Then you can easily perform math and comparisons on the objects. Example: Expand|Select|Wrap|Line Numbers import time   t1 = "12:24:33" t2 = "14:56:12"   tObj1 = time.mktime(time.localtime()[:3]+time.strptime(t1, "%H:%M:%S")[3:]) tObj2 = time.mktime(time.localtime()[:3]+time.strptime(t2, "%H:%M:%S")[3:])   diff = tObj2-tObj1 print tObj1 > tObj2 print diff Output: Expand|Select|Wrap|Line Numbers >>> False 9099.0 >>>  Mar 27 '11 #2

 P: 2 Hello bvdet !! Actually my query about my program is that: i have to make a program which takes the two times (start time and end time) from the user. Then, i take the third time interval (say in minutes)from the user. Now in my program: suppose the user gives, start time : 12:00:00 and end time: 13:00:00 and time interval : 5 minutes so it will compare in my file XYZ.TXT the start time string "12:00:00" . If in the file it finds the time say, 12:30:20 then it starts from this time and after every 5 minutes (time interval) it reads from the file and prints the time , which should lie between 13:00:00 (end time) please do help me with this !! Mar 31 '11 #3

 Expert Mod 2.5K+ P: 2,851 I have shown you how to create a struct_time object with the time module. To increment a given struct_time object by 5 minutes: Expand|Select|Wrap|Line Numbers >>> time.ctime(tObj1+5*60) 'Thu Mar 31 12:29:33 2011' >>>  The time can be extracted from the string using string methods: Expand|Select|Wrap|Line Numbers >>> time.ctime(tObj1+5*60).split() '12:29:33' >>>  Perhaps you can study python documentation on the time module and the example code I have posted to develop the code for your application. Post back if you have any specific questions about your code. Mar 31 '11 #4 