2

I want to create an hourly object list from a time range.

Is there any function like python pandas.timerange in c#?

pandas.time_range("11:00", "21:30", freq="30min")
Alvin
  • 8,219
  • 25
  • 96
  • 177
  • You will have to make your own `TimeSpan`, though this only is a relative span of time, not a static start-end time. – gunr2171 Oct 31 '13 at 15:21
  • If you're asking for a library: try DDay.iCal or NodaTime. If you want to implement it yourself, [use the search](http://stackoverflow.com/questions/3738748/create-an-array-or-list-of-all-dates-between-two-dates). – CodeCaster Oct 31 '13 at 15:21
  • The only part that can't be done with standard loops and `DateTime` parsing is the paring of `30min`. – D Stanley Oct 31 '13 at 15:24
  • Hourly frequence with 30 minutes? Do you need `DateTime`s or `TimeSpan`s? – Tim Schmelter Oct 31 '13 at 15:25
  • Every hour / minutes. – Alvin Oct 31 '13 at 15:28

2 Answers2

6

As an option, take advantage of MoreLInq Generate Method:

//variables used in both examples
var start = TimeSpan.FromHours(11);
var end = TimeSpan.FromHours(21).Add(TimeSpan.FromMinutes(30));

MoreEnumerable.Generate(start, span => span.Add(TimeSpan.FromMinutes(30)))
              .TakeWhile(span => span <= end)

"Native" Linq query is a bit uglier:

Enumerable.Range(0, int.MaxValue)
          .Select(multiplier => start.Add(TimeSpan.FromMinutes(30 * multiplier)))
          .TakeWhile(span => span <= end)

both queries produce:

11:00:00 
11:30:00 
12:00:00 
12:30:00 
13:00:00 
13:30:00 
14:00:00 
  ...
21:00:00 
21:30:00 
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
1

Here's a function that takes a start/end time and # of minutes between:

public IEnumerable<DateTime> GetTimeRange(DateTime startTime, DateTime endTime, int minutesBetween)
{
   int periods = (int)(endTime - startTime).TotalMinutes / minutesBetween;  
   return Enumerable.Range(0,periods+1)
                    .Select (p => startTime.AddMinutes(minutesBetween * p));
}

You can just parse the initial strings when calling the function:

var times = GetTimeRange(DateTime.Parse("11:00"),DateTime.Parse("21:30"),30);
D Stanley
  • 149,601
  • 11
  • 178
  • 240