-1

I am trying to code a function where it calculates the date interval with x amount of seconds before the given_date. Each index of the previouse_dates is the time in seconds that comes before the given_date.

import numpy as np

given_date = np.datetime64('2017-09-15 11:40:30')
previouse_dates= np.datetime64([90, 150, 3600]) #in seconds

Expected output

[2017-09-15 11:39:00  2017-09-15 11:38:00  2017-09-15 10:40:30]
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
tony selcuk
  • 709
  • 3
  • 11

2 Answers2

1

90 seconds isn't a date or a time (thus not a np.datetime64) - it's a time period, and thus a np.timedelta64. Here the 'm' in np.array([90, 150, 3600], 'm') means timedelta64:

>>> given_date = np.datetime64('2017-09-15 11:40:30')
>>> previous_dates = np.array([90, 150, 3600], 'm') # 'm' means `timedelta64`
>>> previous_dates
array([  90,  150, 3600], dtype=timedelta64)
>>> given_date - previous_dates
array(['2017-09-15T11:39:00', '2017-09-15T11:38:00',
       '2017-09-15T10:40:30'], dtype='datetime64[s]')
ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

The solution @forcebru gave works just fine, I just wanted to point out two additional things here:

import numpy as np

given_date = np.datetime64('2017-09-15 11:40:30')
previous_dates = np.array([90, 150, 3600])  # since it's just seconds, no 'm' needed
print(given_date - previous_dates)  # @forcebru solution still works

# you just subtract seconds, so that works, but if you'd want to do something else
fdates = np.vectorize(lambda d: given_date - np.timedelta64(d, 's'))
result = fdates(previous_dates)
print(result)

The second part gives you the same result, but of course you could do different, or slightly more complicated things in the lambda.

Since you're just subtracting seconds, you may as well use the simpler solution and you don't even need the 'm' indication, as the integers will be interpreted as seconds when subtracted from a time.

And since you typically don't want to (and shouldn't need to) keep lambdas around, you can save a line:

result = np.vectorize(lambda d: given_date - np.timedelta64(d, 's'))(previous_dates)
print(result)

(or even just skip the assignment to result and print it directly, of course)

Grismar
  • 27,561
  • 4
  • 31
  • 54