Saturday, July 20, 2013

Generating a Time Interval Based String

Problem :  Need to generate time divided string for time series representation of data. The data can be in 1 minute interval or can be 15 minute interval or can be 1 hour interval. 

Sample Output: 
  • if  timeInterval in 1 min : '01/01/2001 00:00~01/01/2001 00:01'............23:58,23:59,24:00
  • if  timeInterval in 15 min : '01/01/2001 00:00~01/01/2001 00:15'.......,
  • if  timeInterval in 30 min : 01/01/2001 00:00~01/01/2001 00:30'...........
Solution:
Lets think , we need to travel through the day based on time interval - can be of 1 min , 15 min , 30 min , 60 min till the end of day. 
So start condition is : 'startDate 00:00'
timeInterval : deltaT 
end Condition when the day gets over so = startDate+ 1 day
Below is the python code that does just that :
from datetime import timedelta,datetime  
timeGrain = 15 # Can be 30 or so  
deltaT= timedelta(minutes=int(timeGrain)) 
startDate = datetime.datetime.strptime(inputDateTime,'%Y-%m-%d %H:%M:%S') # Convert  String to Date time 
endDate= (startDate+timedelta(days=1))  # End Condition 
while startDate != endDate:
    var = startDate
    nextDateTime = startDate+ deltaT
    keyList.append(str(var)+'~'+str(nextDateTime))
    startDate =nextDateTime
   
And the output :
['2013-03-01 00:00:00~2013-03-01 00:15:00', '2013-03-01 00:15:00~2013-03-01 00:3 0:00', '2013-03-01 00:30:00~2013-03-01 00:45:00', '2013-03-01 00:45:00~2013-03-0 1 01:00:00', '2013-03-01 01:00:00~2013-03-01 01:15:00', '2013-03-01 01:15:00~201 3-03-01 01:30:00', '2013-03-01 01:30:00~2013-03-01 01:45:00', '2013-03-01 01:45: 00~2013-03-01 02:00:00', '2013-03-01 02:00:00~2013-03-01 02:15:00', '2013-03-01 02:15:00~2013-03-01 02:30:00', '2013-03-01 02:30:00~2013-03-01 02:45:00', '2013- 03-01 02:45:00~2013-03-01 03:00:00', '2013-03-01 03:00:00~2013-03-01 03:15:00']

So we are good to go with timedelta object one can iterate over seconds , minutes and days



No comments:

Post a Comment