This notebook demonstrates how to formulate and download subsets of NetCDF data from a THREDDS Data Server using Python. We will construct download URLs automatically so that many files can be retrieved with a short, reproducible script.
Import the modules for this notebook
To begin, import the two modules necessary for this notebook:
import requests
import osA Chlorophyll Example¶
In this example, we’ll examine steps to obtain files from the Ocean Color Climate Change Initiative (OC-CCI) 1 km chlorophyll-a product. As indicated on the OC-CCI data page, this data product is available via THREDDS.
Each dataset in THREDDS is searchable through a dedicated catalogue. For example, OC-CCI data catalogue is located at https://
For example, let’s examine the file for January 1, 2026 available HERE. On this page, we can input some spatial bounds for our query and retrieve a url for our subsetted file at the bottom of the page. For a longitude range 53.4°W to 49°W and a latitude range of 63.5°N to 65°N, this takes the following form:
https://rsg.pml.ac.uk/thredds/ncss/cci/v6.0-1km-release/geographic/2026/
ESACCI-OC-L3S-OC_PRODUCTS-MERGED-1D_DAILY_1km_GEO_PML_OCx_QAA-20260101-fv6.0_1km.nc?var=chlor_a&
north=65&west=-53.4&east=-49&south=63.5&
disableProjSubset=on&horizStride=1&
time_start=2026-01-01T00%3A00%3A00Z&
time_end=2026-01-01T00%3A00%3A00Z&timeStride=1&accept=netcdfTo download this particular file, we can use an HTML get request (equivalent to entering this url in your brower). However, we can also leverage this same url structure to request the same data product on different dates - we just need to change the date information in the url. Specifically, we just need to update the following information:
the year
2026the date strings
20260101and2026-01-01
Similarly, we could also query a different regional subset by updating the longitude and latitude bounds. Let’s use this information below to loop through our dates of interest and download a series of files:
Defining a Download Loop¶
Here, we’ll use the url information provided above to write a loop which will download a series of individual files in a given date and geographic range. This is specific for the data product above, but could easily be adapted to any data set accessible on THREDDS when a new url stucture is provided. Let’s walk through a few steps
Define the destination file path¶
First, let’s define a location where the data will be downloaded:
# define the path to the folder where the data will be downloaded
download_folder = '../data/thredds'Define a query¶
Next, define the download query for the location and time of interest:
# define a geographic bounding box
min_lon = -53.4
max_lon = -49
min_lat = 63.5
max_lat = 65
# define a temporal range
min_year = 2018
max_year = 2018Make a list of download URLs and filenames¶
Next, make a list of all urls and file names to download. This will leverage the file-specific information identified above:
# define the base url
base_url = 'https://rsg.pml.ac.uk/thredds/ncss/cci/v6.0-1km-release/geographic/'
# make a list of URLs corresponding to the file date
file_urls = []
for year in range(min_year,max_year+1):
for month in range(1,13):
# determine the number of days in this month
if month in [1,3,5,7,8,10,12]:
n_days = 31
elif month in [4,6,9,11]:
n_days =30
else:
if year%4==0:
n_days = 29
else:
n_days = 28
# for each date, add the url and file name information to the list
for day in range(1,n_days+1):
# construct the url from the base url
url = base_url
url += '/'+str(year)
# add the file name information
yr = str(year)
mo = '{:02d}'.format(month)
dy = '{:02d}'.format(day)
filename = 'ESACCI-OC-L3S-OC_PRODUCTS-MERGED-1D_DAILY_1km_GEO_PML_OCx_QAA-'+yr+mo+dy+'-fv6.0_1km.nc'
url += '/'+filename
# add the variable information
url += '?var=chlor_a&'
# add the geographic information
url += 'north='+str(max_lat)+'&'
url += 'west='+str(min_lon)+'&'
url += 'east='+str(max_lon)+'&'
url += 'south='+str(min_lat)+'&'
# add some information for the projection and the geographic "stride"
url += 'disableProjSubset=on&horizStride=1&'
# add the temporal range
url += 'time_start='+yr+'-'+mo+'-'+dy+'T00%3A00%3A00Z&'
url += 'time_end='+yr+'-'+mo+'-'+dy+'T00%3A00%3A00Z&'
# add some information for the temporal stride
url += 'timeStride=1&accept=netcdf'
# add the url to the list
file_urls.append((url, filename))Compare this code with the THREDDS url provided above to examine how this code was constructed.
Download the data¶
Now that all of the urls are listed, we just need to use a get request to obtain each one:
# loop through each url
for i in range(len(file_urls)):
url = file_urls[i][0]
file_name = file_urls[i][1]
# if we dont have the file, then download it
if file_name not in os.listdir(download_folder):
print('Downloading file '+str(i+1)+' of '+str(len(file_urls))+')')
output_file = os.path.join(download_folder,file_name)
with requests.get(url, stream=True, allow_redirects=True) as r:
r.raise_for_status()
with open(output_file, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)When the download is complete, we’re ready for analysis!
Merging Files¶
Note that the above scripts will download a series of daily files - one per day. While many of the lab examples in this “book” work with individual files in loops, it can also be convenient to work with a single, stacked file. If this is desirable the xarray package provides a convenient function for this purpose, provided that the files already have a time dimension.
The following code shows one example for stacking files in this fashion for a given year, assuming the files have the format listed above:
import xarray as xr
# determine a year for the stacking
year = 2018
# concatenate all files along the time dimension
ds = xr.open_mfdataset(os.path.join(download_folder,
"ESACCI-OC-L3S-OC_PRODUCTS-MERGED-1D_DAILY_1km_GEO_PML_OCx_QAA-"+str(year)+"*-fv6.0_1km.nc"),
concat_dim="time", combine="nested")
# write the merged dataset to a new file
ds.to_netcdf(os.path.join(download_folder,
"ESACCI-OC-L3S-OC_PRODUCTS-MERGED-1D_DAILY_1km_GEO_PML_OCx_QAA-"+str(year)+"-fv6.0_1km.nc"))