Skip to content

How to find the time nearest to local 2 pm for every day? #7320

Answered by zxdawn
zxdawn asked this question in Q&A
Discussion options

You must be logged in to vote

Find out the solution:

import numpy as np
import pandas as pd
import xarray as xr

# create data
lon = np.arange(-180, 180, 10)
lat = np.arange(-90, 90.5, 0.5)
time = pd.date_range('2019-08-10 00:00', '2019-08-10 21:00', freq='3h')
data = np.random.rand(len(time), len(lat), len(lon))
data = xr.DataArray(data, dims=['time', 'lat', 'lon'], coords={'time': time, 'lat': lat, 'lon': lon})
hour_offset = (lon+7.5)//15

time_3d = np.broadcast_to(time.hour.values[:, np.newaxis, np.newaxis], (len(time), len(lat), len(lon)))
timedelta_3d = np.broadcast_to(hour_offset[np.newaxis, np.newaxis, :], (len(time), len(lat), len(lon)))
min_index = abs(time_3d + timedelta_3d - 14).argmin(axis=0).astype('int')…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by zxdawn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant