2

Trying to create an array from a startdate to an enddate with a slot for every second. Pretty much like numpy.linspace(startdate,enddate,number_of_seconds_inbetween). Whats the easiest/fastest way to do this?

2 Answers 2

5

np.arange does it more or less out of the box:

np.arange("2000-01-01","2000-01-02",dtype="M8[s]")
# array(['2000-01-01T00:00:00', '2000-01-01T00:00:01',
#        '2000-01-01T00:00:02', ..., '2000-01-01T23:59:57',
#        '2000-01-01T23:59:58', '2000-01-01T23:59:59'],
#       dtype='datetime64[s]')
Sign up to request clarification or add additional context in comments.

5 Comments

Ah nice... didn't think this was possible directly using np.arange
Now the question is why there isn't a np.linspace implementation for this. XD
linspace produces evenly spaced floats. The datetime steps are discrete - days, minutes etc
@hpaulj linspace can output "exact" dtypes like int, so in principle it should be possible to make datetime64 work in the same way.
linspace is Python code. The current linspace (1.16) works by creating a arange(N) and scaling with the end points (which may be arrays). Math with datetime64 is limited to subtraction. But np.array("2000-01-01",'M8[D]') + np.linspace(0, 10, 11).astype("timedelta64[D]") does work.
1
def linspace_datetime64(start_date, end_date, n):
    return np.linspace(0, 1, n) * (end_date - start_date) + start_date

Example usage:

>>> start_date = np.datetime64('2008-01-01')
>>> end_date = np.datetime64('2009-01-01')
>>> linspace_datetime64(start_date, end_date, 12)
array(['2008-01-01', '2008-02-03', '2008-03-07', '2008-04-09',
       '2008-05-13', '2008-06-15', '2008-07-18', '2008-08-20',
       '2008-09-23', '2008-10-26', '2008-11-28', '2009-01-01'],
      dtype='datetime64[D]')

1 Comment

The answer is not complete. It doesn't show how to get every second between any two dates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.