I'm trying to create a standalone python script that uses PyQGIS to create a map with a raster layer read from WMS.
My idea was to create a QgsRasterLayer with provider set to wms with the time argument encoded into the URL.
To test, I've just tried adding them in the python console within QGIS:
# default time
url1 = "layers=MCD43C3_M_BSA&styles=rgb&bbox=-180,-90,180,90&height=512&width=512&crs=CRS:84&format=image/png&url=https://neo.gsfc.nasa.gov/wms/wms?version%3D1.3.0"
selected time 2017-01-01
url2 = "layers=MCD43C3_M_BSA&styles=rgb&bbox=-180,-90,180,90&height=512&width=512&crs=CRS:84&format=image/png&time=2017-01-01&url=https://neo.gsfc.nasa.gov/wms/wms?version%3D1.3.0"
iface.addRasterLayer(url1, "default", "wms")
iface.addRasterLayer(url2, "selection", "wms")
However, I get the same raster both times, and the developer panel indicates the time parameter is not included in the query:
Is there a simple way I'm missing where I can select a date out of the available time steps from a WMS layer?
Edit:
til_b's excellent answer below has shown that one can use owslib to interact with the WMS server and with that easily select dates from the layer's time axis.
The issue is the intended use:
I want to use this WMS source to create a map using PyQGIS. I could indeed try to obtain the image some other way and then plug in into PyQGIS for mapping, but that seems overly complicated and has some gotchas:
- I need to define the image shape beforehand (I suppose that could be calculated from extent, resolution, dpi etc.)
- Some servers limit the max image shape to tiles (e.g. 512) so I'd need to get multiple tiles and stitch them together myself
- I need to encode the geoinfo myself if I want to map it together with other geospatial data
Doing all of this myself feels a lot like re-inventing the wheel - particularly it's already being handled by PyQGIS with the notable issue that I can't select a date!
I really think there must be a way to do this with PyQGIS since you can clearly do it with the GUI. Either it's a bit more elaborate (maybe using the Temporal Controller perhaps), or I'm just missing the obvious! (or neither and it's a bug ... )



service=WMS&andrequest=GetMap&. The other odd thing about the developer panel response is use of different CRS, and swapping of bbox – nmtoken Nov 04 '22 at 11:31service&requestquery args? In any case, using these links works just fine for me (besides the missingTIMEarg). Regarding CRS: CRS:84 is equivalent to EPSG:4326, maybe something else going on behind the QGIS scenes. The WMS service publishesCRS:84why I need to use it in the request – Val Nov 04 '22 at 11:37OWSlibis fine if I can get an image for a defined area that then can be mapped with PyQGIS – Val Nov 07 '22 at 12:07