Python generate dates series

49,298

Solution 1

Well, obviously you start at the start time, loop until you reach the end time and increment inbetween.

import datetime

dt = datetime.datetime(2010, 12, 1)
end = datetime.datetime(2010, 12, 30, 23, 59, 59)
step = datetime.timedelta(seconds=5)

result = []

while dt < end:
    result.append(dt.strftime('%Y-%m-%d %H:%M:%S'))
    dt += step

Fairly trivial.

Solution 2

I just felt that it might be worthwhile to note that pandas also has this functionality. Depending on what case you are dealing with exactly, pandas might be a worthy tool to invest time in.

import pandas as pd 
times = pd.date_range('2012-10-01', periods=289, freq='5min')

This returns a pandas timeseries-index. Which can be converted to numpy arrays.

np.array(times)

Solution 3

this is my variant for python3, but it's easy could be converted into python2.6 code:

import datetime as dt

dt1 = dt.datetime(2010, 12, 1)
dt2 = dt.datetime(2010, 12, 12, 23, 59, 59)

time_step = 5 # secoonds
delta = dt2 - dt1

delta_sec = delta.days * 24 * 60 * 60 + delta.seconds

res = [dt1 + dt.timedelta(0, t) for t in range(0, delta_sec, time_step)]
Share:
49,298
Rafał Kot
Author by

Rafał Kot

Updated on March 07, 2020

Comments

  • Rafał Kot
    Rafał Kot about 4 years

    How can i generate array with dates like this:

    Timestamps in javascript miliseconds format from 2010.12.01 00:00:00 to 2010.12.12.30 23.59.59 with step 5 minutes.

    ['2010.12.01 00:00:00', '2010.12.01 00:05:00','2010.12.01 00:10:00','2010.12.01 00:15:00', ...]
    
  • cgi
    cgi over 13 years
    I miss one thing in this answer: elements of the array are dates, not strings... it's can be fixed with follow: str(dt1 + dt.timedelta(0, t)) ... format of the result is just as you need
  • Lennart Regebro
    Lennart Regebro over 13 years
    No conversion needed, that runs in both Python 2 and 3 (as do my example).
  • mtrw
    mtrw over 13 years
    The format string should be '%Y.%m.%d ...' to strictly match the question.
  • cgi
    cgi over 13 years
    In python2 it's beter to use xrange, not range
  • Lennart Regebro
    Lennart Regebro over 13 years
    Well, I'm not here to implement specifications, I charge money for that. :)
  • Lennart Regebro
    Lennart Regebro over 13 years
    Sure, but it's half a million int objects that are in memory for a few seconds. If you don't have that memory you need a new computer. ;)