diff --git a/pylib/iemweb/autoplot/scripts/p63.py b/pylib/iemweb/autoplot/scripts/p63.py index 212fcbba2..7d4dfdbf1 100644 --- a/pylib/iemweb/autoplot/scripts/p63.py +++ b/pylib/iemweb/autoplot/scripts/p63.py @@ -8,7 +8,7 @@ expect to set 365 records the first year, 183 the second, and so on... """ -import datetime +from datetime import datetime import pandas as pd from pyiem.database import get_dbconnc @@ -37,7 +37,7 @@ def plotter(ctx: dict): pgconn, cursor = get_dbconnc("coop") syear = sts.year if sts.month == 1 and sts.day == 1 else (sts.year + 1) syear = max(syear, 1893) - eyear = datetime.datetime.now().year + eyear = datetime.now().year cursor.execute( """ diff --git a/pylib/iemweb/autoplot/scripts/p64.py b/pylib/iemweb/autoplot/scripts/p64.py index 8e56d9799..694e73d19 100644 --- a/pylib/iemweb/autoplot/scripts/p64.py +++ b/pylib/iemweb/autoplot/scripts/p64.py @@ -9,7 +9,7 @@ """ import calendar -import datetime +from datetime import date, datetime, timedelta import numpy as np import pandas as pd @@ -63,7 +63,7 @@ def get_data(ctx): if ab is None: raise NoDataFound("No Data Found.") syear = max(1893, ab.year) - eyear = datetime.datetime.now().year + eyear = datetime.now().year snow = np.zeros((eyear - syear + 1, 366)) snowd = np.zeros((eyear - syear + 1, 366)) @@ -112,9 +112,7 @@ def get_data(ctx): color = "b" else: color = "r" - dt = datetime.date(year, 1, 1) + datetime.timedelta( - days=(int(idx) + 183 - 1) - ) + dt = date(year, 1, 1) + timedelta(days=int(idx) + 183 - 1) rows.append( dict( year=year, @@ -184,7 +182,7 @@ def plotter(ctx: dict): ) fig = figure(title=title, apctx=ctx) plot_yearly_trend(fig, df) - ax = fig.add_axes([0.08, 0.11, 0.36, 0.79]) + ax = fig.add_axes((0.08, 0.11, 0.36, 0.79)) ax.scatter( df["snow_doy"], @@ -212,7 +210,7 @@ def plotter(ctx: dict): ax.grid(True) ax.set_ylim(bottom=0) ax2 = ax.twinx() - ptile = np.percentile(df["snow_doy"].values, np.arange(100)) + ptile = np.percentile(df["snow_doy"].to_numpy(), np.arange(100)) ax2.plot(ptile, np.arange(100), lw=2, color="k") ax2.set_ylabel( ("Frequency of %s Date (CDF) [%%] (black line)") diff --git a/pylib/iemweb/autoplot/scripts/p65.py b/pylib/iemweb/autoplot/scripts/p65.py index 6ec9974d3..05aa0e18a 100644 --- a/pylib/iemweb/autoplot/scripts/p65.py +++ b/pylib/iemweb/autoplot/scripts/p65.py @@ -5,7 +5,7 @@ """ import calendar -import datetime +from datetime import date, datetime, timedelta import pandas as pd from pyiem.database import get_sqlalchemy_conn @@ -19,7 +19,7 @@ def get_description(): """Return a dict describing how to call this plotter""" desc = {"description": __doc__, "data": True} - today = datetime.date.today() + today = date.today() desc["arguments"] = [ ARG_STATION, dict( @@ -44,8 +44,8 @@ def plotter(ctx: dict): station = ctx["station"] month = ctx["month"] mydir = ctx["dir"] - ts = datetime.datetime(2000, month, 1) - ets = ts + datetime.timedelta(days=35) + ts = datetime(2000, month, 1) + ets = ts + timedelta(days=35) ets = ets.replace(day=1) days = int((ets - ts).days) diff --git a/pylib/iemweb/autoplot/scripts/p67.py b/pylib/iemweb/autoplot/scripts/p67.py index 036e1d021..09c8caa17 100644 --- a/pylib/iemweb/autoplot/scripts/p67.py +++ b/pylib/iemweb/autoplot/scripts/p67.py @@ -5,7 +5,7 @@ """ import calendar -import datetime +from datetime import datetime import matplotlib.patheffects as PathEffects import pandas as pd @@ -88,7 +88,7 @@ def plotter(ctx: dict): f"{ctx['_sname']}\n" f"Frequency of {threshold}+ knot Wind Speeds by Temperature " f"for {calendar.month_name[month]} " - f"({ab.year}-{datetime.datetime.now().year})\n" + f"({ab.year}-{datetime.now().year})\n" "(must have 3+ hourly observations at the given temperature)" ) (fig, ax) = figure_axes(title=title, apctx=ctx) diff --git a/pylib/iemweb/autoplot/scripts/p71.py b/pylib/iemweb/autoplot/scripts/p71.py index 3094be383..37aa6a1ee 100644 --- a/pylib/iemweb/autoplot/scripts/p71.py +++ b/pylib/iemweb/autoplot/scripts/p71.py @@ -9,7 +9,7 @@ is computed by vector averaging of the wind speed and direction reports. """ -import datetime +from datetime import date, datetime import matplotlib.patheffects as PathEffects import numpy as np @@ -46,13 +46,13 @@ def get_description(): dict( type="year", name="year", - default=datetime.datetime.now().year, + default=datetime.now().year, label="Select Year:", ), dict( type="month", name="month", - default=datetime.datetime.now().month, + default=datetime.now().month, label="Select Month:", ), dict( @@ -88,7 +88,7 @@ def plotter(ctx: dict): plot_units = ctx["units"] year = ctx["year"] month = ctx["month"] - sts = datetime.date(year, month, 1) + sts = date(year, month, 1) with get_sqlalchemy_conn("iem") as conn: df = pd.read_sql( """ diff --git a/pylib/iemweb/autoplot/scripts/p72.py b/pylib/iemweb/autoplot/scripts/p72.py index 2b5d844b4..0fb11317d 100644 --- a/pylib/iemweb/autoplot/scripts/p72.py +++ b/pylib/iemweb/autoplot/scripts/p72.py @@ -14,7 +14,7 @@ plots for a single county/zone/parish at a time. """ -import datetime +from datetime import datetime import pandas as pd from pyiem.database import get_sqlalchemy_conn @@ -142,7 +142,7 @@ def plotter(ctx: dict): elif ctx["season"] == "winter": months = [12, 1, 2] else: - ts = datetime.datetime.strptime(f"2000-{ctx['season']}-01", "%Y-%b-%d") + ts = datetime.strptime(f"2000-{ctx['season']}-01", "%Y-%b-%d") months = [ts.month] tzname = ctx["_nt"].sts[wfo]["tzname"] diff --git a/pylib/iemweb/autoplot/scripts/p75.py b/pylib/iemweb/autoplot/scripts/p75.py index 4ca93ba10..8f7a09998 100644 --- a/pylib/iemweb/autoplot/scripts/p75.py +++ b/pylib/iemweb/autoplot/scripts/p75.py @@ -2,7 +2,7 @@ Simple plot of seasonal/yearly precipitation totals. """ -import datetime +from datetime import datetime import numpy as np import pandas as pd @@ -76,7 +76,7 @@ def plotter(ctx: dict): pgconn.close() raise NoDataFound("No Data Found.") - today = datetime.datetime.now() + today = datetime.now() thisyear = today.year if season == "spring" and today.month > 5: thisyear += 1 diff --git a/pylib/iemweb/autoplot/scripts/p79.py b/pylib/iemweb/autoplot/scripts/p79.py index f0d713a89..f2247b0d4 100644 --- a/pylib/iemweb/autoplot/scripts/p79.py +++ b/pylib/iemweb/autoplot/scripts/p79.py @@ -6,7 +6,7 @@ relative humidity value is computed. """ -import datetime +from datetime import datetime import matplotlib.ticker as mticker import metpy.calc as mcalc @@ -170,7 +170,7 @@ def plotter(ctx: dict): titles = [ f"{ctx['_sname']}:: ", f"Average Dew Point by Wind Direction (month={month.upper()}) " - f"({max([1973, ab.year])}-{datetime.datetime.now().year})", + f"({max([1973, ab.year])}-{datetime.now().year})", "(must have 3+ hourly obs >= 3 knots at given direction)", ] ax.set_title("\n".join(titles), size=10) diff --git a/pylib/iemweb/autoplot/scripts/p87.py b/pylib/iemweb/autoplot/scripts/p87.py index 4075a118b..66ed6c7c8 100644 --- a/pylib/iemweb/autoplot/scripts/p87.py +++ b/pylib/iemweb/autoplot/scripts/p87.py @@ -8,7 +8,7 @@ """ import calendar -import datetime +from datetime import date import numpy as np import pandas as pd @@ -64,7 +64,7 @@ def get_description(): dict( type="year", name="eyear", - default=datetime.date.today().year, + default=date.today().year, label="End Year of Analysis (inclusive):", ), ] @@ -77,8 +77,8 @@ def plotter(ctx: dict): syear = ctx["syear"] eyear = ctx["eyear"] groupby = ctx["groupby"] - sts = datetime.date(syear, 1, 1) - ets = datetime.date(eyear + 1, 1, 1) + sts = date(syear, 1, 1) + ets = date(eyear + 1, 1, 1) code = ctx["code"] if code == "PSN": code = "+SN" @@ -148,8 +148,8 @@ def plotter(ctx: dict): f"{PDICT2[groupby].replace('group ', '')}" ) fig = figure(apctx=ctx, title=title) - ax = fig.add_axes([0.11, 0.25, 0.7, 0.65]) - cax = fig.add_axes([0.82, 0.04, 0.02, 0.15]) + ax = fig.add_axes((0.11, 0.25, 0.7, 0.65)) + cax = fig.add_axes((0.82, 0.04, 0.02, 0.15)) res = ax.imshow( data, aspect="auto", rasterized=True, interpolation="nearest" @@ -163,7 +163,7 @@ def plotter(ctx: dict): ax.set_ylabel(f"Local Time, {ctx['_nt'].sts[station]['tzname']}") ax.set_yticklabels(("Mid", "4 AM", "8 AM", "Noon", "4 PM", "8 PM")) ax.grid(True) - lax = fig.add_axes([0.11, 0.1, 0.7, 0.15]) + lax = fig.add_axes((0.11, 0.1, 0.7, 0.15)) if groupby == "week": ax.set_xticks(np.arange(0, 55, 7)) lax.bar(np.arange(0, 52), np.ma.sum(data, 0), facecolor="tan") @@ -198,7 +198,7 @@ def plotter(ctx: dict): lax.yaxis.get_major_ticks()[-1].label1.set_visible(False) # Right grid - rax = fig.add_axes([0.81, 0.25, 0.15, 0.65]) + rax = fig.add_axes((0.81, 0.25, 0.15, 0.65)) rax.barh(np.arange(0, 24) - 0.4, np.ma.sum(data, 1), facecolor="tan") rax.set_ylim(-0.5, 23.5) rax.set_yticks([]) diff --git a/pylib/iemweb/autoplot/scripts/p88.py b/pylib/iemweb/autoplot/scripts/p88.py index 918483bce..144ec9e90 100644 --- a/pylib/iemweb/autoplot/scripts/p88.py +++ b/pylib/iemweb/autoplot/scripts/p88.py @@ -7,7 +7,7 @@ reliable/comparable. """ -import datetime +from datetime import date import numpy as np import pandas as pd @@ -92,7 +92,7 @@ def plotter(ctx: dict): raise NoDataFound("Unknown station metadata.") title = ( f"{ctx['_sname']} " - f"({max([ab.year, 1973])}-{datetime.date.today().year})\n" + f"({max([ab.year, 1973])}-{date.today().year})\n" f"Hourly Temp Departure (skies were {PDICT[ctx['which']]} vs all)" ) (fig, ax) = figure_axes(title=title, apctx=ctx) diff --git a/pylib/iemweb/autoplot/scripts/p90.py b/pylib/iemweb/autoplot/scripts/p90.py index cfe7dd4d8..b3be06ae7 100644 --- a/pylib/iemweb/autoplot/scripts/p90.py +++ b/pylib/iemweb/autoplot/scripts/p90.py @@ -90,8 +90,7 @@ away as sometimes it will take 3-5 minutes to generate a map :( """ -from datetime import date, datetime, timedelta -from zoneinfo import ZoneInfo +from datetime import date, datetime, timedelta, timezone import geopandas as gpd import numpy as np @@ -262,8 +261,12 @@ def get_description(): return desc -def do_polygon(ctx: dict): +def get_raster(ctx: dict): """polygon workflow""" + if ctx["geo"] == "ugc": + raise NoDataFound("Sorry, GeoTIFF only works for polygon summaries.") + ctx["sdate"] = ctx["sdate"].replace(tzinfo=timezone.utc) + ctx["edate"] = ctx["edate"].replace(tzinfo=timezone.utc) varname = ctx["v"] if varname == "events": raise NoDataFound("Sorry, not implemented for polygon summaries.") @@ -311,7 +314,7 @@ def do_polygon(ctx: dict): (west, south, east, north) = fema_region_bounds[int(ctx["fema"])] else: (west, south, east, north) = state_bounds[state] - # buffer by 5 degrees so to hopefully get all polys + # buffer by 2 degrees so to hopefully get all polys (west, south) = [x - 2 for x in (west, south)] (east, north) = [x + 2 for x in (east, north)] # create grids @@ -319,13 +322,10 @@ def do_polygon(ctx: dict): if (east - west) > 10: griddelta = 0.02 lons = np.arange(west, east, griddelta) - lon_edges = np.append(lons - griddelta / 2.0, lons[-1] + griddelta / 2.0) lats = np.arange(south, north, griddelta) - lat_edges = np.append(lats - griddelta / 2.0, lats[-1] + griddelta / 2.0) YSZ = len(lats) XSZ = len(lons) lons, lats = np.meshgrid(lons, lats) - lon_edges, lat_edges = np.meshgrid(lon_edges, lat_edges) # lons and lats are the center of the grid cells, so the affine needs # to be adjusted to the upper left corner affine = Affine( @@ -336,8 +336,8 @@ def do_polygon(ctx: dict): 0 - griddelta, north + griddelta / 2.0, ) - ones = np.ones((int(YSZ), int(XSZ))) - counts = np.zeros((int(YSZ), int(XSZ))) + ones = np.ones((YSZ, XSZ)) + counts = np.zeros((YSZ, XSZ)) wfolimiter = "" if ctx["t"] == "cwa": wfolimiter = " wfo = :wfo and " @@ -386,13 +386,14 @@ def do_polygon(ctx: dict): aff = z["mini_raster_affine"] mywest = aff.c mynorth = aff.f - raster = np.flipud(z["mini_raster_array"]) + raster = z["mini_raster_array"] x0 = int((mywest - west) / griddelta) - y1 = int((mynorth - south) / griddelta) - dy, dx = np.shape(raster) - x1 = x0 + dx - y0 = y1 - dy + y0 = int((north - mynorth) / griddelta) + ny, nx = np.shape(raster) + x1 = x0 + nx + y1 = y0 + ny if x0 < 0 or x1 >= XSZ or y0 < 0 or y1 >= YSZ: + # Hmmmmm continue if varname == "lastyear": counts[y0:y1, x0:x1] = np.where( @@ -408,7 +409,11 @@ def do_polygon(ctx: dict): raise NoDataFound("Sorry, no data found for query!") # construct the df ctx["df"] = pd.DataFrame( - {"lat": lats.ravel(), "lon": lons.ravel(), "val": counts.ravel()} + { + "lat": lats.ravel(), + "lon": lons.ravel(), + "val": np.flipud(counts).ravel(), + } ) minv = df["issue"].min() maxv = df["issue"].max() @@ -479,9 +484,7 @@ def do_polygon(ctx: dict): break bins[0] = 0.01 ctx["bins"] = bins - ctx["data"] = counts - ctx["lats"] = lat_edges - ctx["lons"] = lon_edges + return counts, affine, "EPSG:4326" def do_ugc(ctx: dict): @@ -533,9 +536,7 @@ def do_ugc(ctx: dict): data = {} for row in cursor: days = int( - ( - edate - row[1].replace(tzinfo=ZoneInfo("UTC")) - ).total_seconds() + (edate - row[1].replace(tzinfo=timezone.utc)).total_seconds() / 86400.0 ) rows.append( @@ -894,8 +895,8 @@ def do_ugc(ctx: dict): def plotter(ctx: dict): """Go""" # Covert datetime to UTC - ctx["sdate"] = ctx["sdate"].replace(tzinfo=ZoneInfo("UTC")) - ctx["edate"] = ctx["edate"].replace(tzinfo=ZoneInfo("UTC")) + ctx["sdate"] = ctx["sdate"].replace(tzinfo=timezone.utc) + ctx["edate"] = ctx["edate"].replace(tzinfo=timezone.utc) state = ctx["state"] phenomena = ctx["phenomena"] significance = ctx["significance"] @@ -903,10 +904,13 @@ def plotter(ctx: dict): t = ctx["t"] ilabel = ctx["ilabel"] == "yes" geo = ctx["geo"] + grid = None + aff = None + crs = None if geo == "ugc": do_ugc(ctx) elif geo == "polygon": - do_polygon(ctx) + grid, aff, crs = get_raster(ctx) subtitle = f"based on IEM Archives {ctx.get('subtitle', '')}" if t == "cwa": @@ -988,17 +992,15 @@ def plotter(ctx: dict): is_firewx=(phenomena == "FW"), ) else: - res = mp.pcolormesh( - ctx["lons"], - ctx["lats"], - ctx["data"], - ctx["bins"], + mp.imshow( + grid, + aff, + crs, + clevs=ctx["bins"], cmap=cmap, units=ctx["units"], extend=ctx.get("extend", "both"), ) - # Cut down on SVG et al size - res.set_rasterized(True) if ctx["drawc"] == "yes": mp.drawcounties() diff --git a/pylib/iemweb/autoplot/scripts/p92.py b/pylib/iemweb/autoplot/scripts/p92.py index 0cc0e5f7a..2d1deb963 100644 --- a/pylib/iemweb/autoplot/scripts/p92.py +++ b/pylib/iemweb/autoplot/scripts/p92.py @@ -5,7 +5,7 @@ of days prior to that date. """ -import datetime +from datetime import date import pandas as pd from pyiem.exceptions import NoDataFound @@ -44,7 +44,7 @@ def get_description(): ), dict( type="date", - default=datetime.date.today().strftime("%Y/%m/%d"), + default=date.today().strftime("%Y/%m/%d"), optional=True, label="Retroactive Date of Plot:", name="edate", diff --git a/pylib/iemweb/autoplot/scripts/p93.py b/pylib/iemweb/autoplot/scripts/p93.py index 2e0196d13..9661e9f03 100644 --- a/pylib/iemweb/autoplot/scripts/p93.py +++ b/pylib/iemweb/autoplot/scripts/p93.py @@ -24,7 +24,7 @@ of wind chill, it is less than or equal to.

""" -import datetime +from datetime import date import numpy as np import pandas as pd @@ -79,14 +79,14 @@ def get_description(): dict( type="year", min=1973, - default=datetime.date.today().year, + default=date.today().year, name="eyear", label="End year (inclusive, if data available) for plot:", ), dict( type="year", min=1973, - default=datetime.date.today().year, + default=date.today().year, name="year", label="Year to Highlight:", ), @@ -123,7 +123,7 @@ def get_doylimit(ytd, varname): return "" if varname not in ["windchill", "tmpf_cold", "dwpf_cold"]: return "and extract(doy from valid) < extract(doy from 'TODAY'::date)" - if datetime.date.today().month > 7: + if date.today().month > 7: res = "and extract(doy from valid) < extract(doy from 'TODAY'::date) " if varname in ["windchill", "tmpf_cold", "dwpf_cold"]: res += "and extract(month from valid) > 6" @@ -139,8 +139,8 @@ def plotter(ctx: dict): """Go""" station = ctx["zstation"] highlightyear = ctx["year"] - sdate = datetime.date(ctx["syear"], 1, 1) - edate = datetime.date(ctx["eyear"] + 1, 1, 1) + sdate = date(ctx["syear"], 1, 1) + edate = date(ctx["eyear"] + 1, 1, 1) ytd = ctx["ytd"] varname = ctx["var"] inc = ctx["inc"] @@ -213,7 +213,7 @@ def plotter(ctx: dict): title = "" if varname in ["windchill", "tmpf_cold", "dwpf_cold"]: title = "1 Jul " - title = f"{title}till {datetime.date.today():%-d %b}" + title = f"{title}till {date.today():%-d %b}" title = "Entire Year" if ytd == "no" else title title = ( f"{ctx['_sname']} ({minyear}-{maxyear})\n" diff --git a/pylib/iemweb/autoplot/scripts/p94.py b/pylib/iemweb/autoplot/scripts/p94.py index f243ada14..9c1cf58e3 100644 --- a/pylib/iemweb/autoplot/scripts/p94.py +++ b/pylib/iemweb/autoplot/scripts/p94.py @@ -9,7 +9,7 @@ observation over the years is problematic. """ -import datetime +from datetime import date import numpy as np import pandas as pd @@ -72,7 +72,7 @@ def plotter(ctx: dict): ab = ctx["_nt"].sts[station]["archive_begin"] if ab is None: raise NoDataFound("Unknown station metadata.") - title = f"{ctx['_sname']} ({ab.year}-{datetime.date.today().year})" + title = f"{ctx['_sname']} ({ab.year}-{date.today().year})" subtitle = "Bias of 24 Hour 'Day' Split for Average High + Low Temp" (fig, ax) = figure_axes(title=title, subtitle=subtitle, apctx=ctx) ax.plot( diff --git a/pylib/iemweb/autoplot/scripts/p95.py b/pylib/iemweb/autoplot/scripts/p95.py index 756f98e5b..d662e5dc5 100644 --- a/pylib/iemweb/autoplot/scripts/p95.py +++ b/pylib/iemweb/autoplot/scripts/p95.py @@ -8,7 +8,7 @@ of a given SOI to be felt in the midwestern US. """ -import datetime +from datetime import date import matplotlib.colors as mpcolors import numpy as np @@ -55,7 +55,7 @@ def get_description(): ), dict( type="text", - default=str(datetime.date.today().year), + default=str(date.today().year), name="year", label="Year(s) to Highlight in Chart (comma delimited)", ), @@ -66,8 +66,8 @@ def get_description(): def title(wanted): """Make a title""" - t1 = datetime.date(2000, wanted[0], 1) - t2 = datetime.date(2000, wanted[-1], 1) + t1 = date(2000, wanted[0], 1) + t2 = date(2000, wanted[-1], 1) return "Avg Precip + Temp for %s%s" % ( t1.strftime("%B"), " thru %s" % (t2.strftime("%B"),) if wanted[0] != wanted[-1] else "", @@ -133,10 +133,10 @@ def plotter(ctx: dict): title2 = f"{ctx['_sname']} :: {title(wanted)}" subtitle = "%s SOI (3 month average)" % ( - datetime.date(2000, wantmonth, 1).strftime("%B"), + date(2000, wantmonth, 1).strftime("%B"), ) fig = figure(title=title2, subtitle=subtitle, apctx=ctx) - ax = fig.add_axes([0.07, 0.12, 0.53, 0.75]) + ax = fig.add_axes((0.07, 0.12, 0.53, 0.75)) cmap = get_cmap(ctx["cmap"]) zdata = np.arange(-2.0, 2.1, 0.5) @@ -186,7 +186,7 @@ def plotter(ctx: dict): ax.set_ylabel( (r"Average Temperature $^\circ$F, " "Avg: %.1f") % (np.average(ys),) ) - ax2 = fig.add_axes([0.67, 0.55, 0.28, 0.35]) + ax2 = fig.add_axes((0.67, 0.55, 0.28, 0.35)) ax2.scatter(df["soi3m"].values, df["tmpf"].values) ax2.set_xlabel("<-- El Nino :: SOI :: La Nina -->") ax2.set_ylabel(r"Avg Temp $^\circ$F") @@ -206,12 +206,12 @@ def plotter(ctx: dict): ) ax2.grid(True) - ax3 = fig.add_axes([0.67, 0.1, 0.28, 0.35]) + ax3 = fig.add_axes((0.67, 0.1, 0.28, 0.35)) ax3.scatter(df["soi3m"].values, df["precip"].values) ax3.set_xlabel("<-- El Nino :: SOI :: La Nina -->") ax3.set_ylabel("Total Precip [inch]") slp, intercept, r_value, _, _ = stats.linregress( - df["soi3m"].values, df["precip"].values + df["soi3m"].to_numpy(), df["precip"].to_numpy() ) y1 = -2.0 * slp + intercept y2 = 2.0 * slp + intercept diff --git a/pylib/iemweb/autoplot/scripts100/p104.py b/pylib/iemweb/autoplot/scripts100/p104.py index 155719592..bdc016dc5 100644 --- a/pylib/iemweb/autoplot/scripts100/p104.py +++ b/pylib/iemweb/autoplot/scripts100/p104.py @@ -9,7 +9,7 @@ comparable plot to this one is of suply vs demand. """ -import datetime +from datetime import datetime, timedelta import numpy as np import pandas as pd @@ -23,13 +23,13 @@ def get_description(): """Return a dict describing how to call this plotter""" desc = {"description": __doc__, "data": True} - today = datetime.datetime.today() - datetime.timedelta(days=1) + today = datetime.today() - timedelta(days=1) desc["arguments"] = [ ARG_STATION, dict( type="date", name="date1", - default=(today - datetime.timedelta(days=90)).strftime("%Y/%m/%d"), + default=(today - timedelta(days=90)).strftime("%Y/%m/%d"), label="Start Date:", min="1893/01/01", ), @@ -85,7 +85,7 @@ def plotter(ctx: dict): (fig, ax) = figure_axes(title=title, apctx=ctx) - interval = datetime.timedelta(days=days2) + interval = timedelta(days=days2) lbls = [] lbls2 = [] @@ -96,9 +96,9 @@ def plotter(ctx: dict): now = date1 while now <= date2: - sdays = [] - for i in range(0, 0 - days, -1): - sdays.append((now + datetime.timedelta(days=i)).strftime("%m%d")) # noqa + sdays = [ + f"{(now - timedelta(days=i)):%m%d}" for i in range(0, 0 - days, -1) + ] cursor.execute( """ SELECT avg(p), stddev(p), avg(t), stddev(t), diff --git a/pylib/iemweb/autoplot/scripts100/p108.py b/pylib/iemweb/autoplot/scripts100/p108.py index 6fba9fc36..2a4e39950 100644 --- a/pylib/iemweb/autoplot/scripts100/p108.py +++ b/pylib/iemweb/autoplot/scripts100/p108.py @@ -7,7 +7,7 @@ site. """ -import datetime +from datetime import date, datetime, timedelta import numpy as np import pandas as pd @@ -28,7 +28,7 @@ def get_description(): """Return a dict describing how to call this plotter""" desc = {"description": __doc__, "data": True} - today = datetime.date.today() + today = date.today() if today.month < 5: today = today.replace(year=today.year - 1, month=10, day=1) sts = today.replace(month=5, day=1) @@ -137,7 +137,7 @@ def plotter(ctx: dict): df[glabel + "_diff"] = df["o" + glabel] - df["c" + glabel] xlen = int((edate - sdate).days) + 1 # In case of leap day - years = (datetime.datetime.now().year - ab.year) + 1 + years = (datetime.now().year - ab.year) + 1 acc = np.zeros((years, xlen)) acc[:] = np.nan pacc = np.zeros((years, xlen)) @@ -146,7 +146,7 @@ def plotter(ctx: dict): sacc[:] = np.nan if whichplots == "all": fig = figure(figsize=(9, 12), apctx=ctx) - ax1 = fig.add_axes([0.1, 0.7, 0.8, 0.2]) + ax1 = fig.add_axes((0.1, 0.7, 0.8, 0.2)) ax2 = fig.add_axes( [0.1, 0.6, 0.8, 0.1], sharex=ax1, facecolor="#EEEEEE" ) @@ -158,33 +158,33 @@ def plotter(ctx: dict): ) elif whichplots == "gdd": fig = figure(apctx=ctx) - ax1 = fig.add_axes([0.14, 0.31, 0.8, 0.57]) + ax1 = fig.add_axes((0.14, 0.31, 0.8, 0.57)) ax2 = fig.add_axes( [0.14, 0.11, 0.8, 0.2], sharex=ax1, facecolor="#EEEEEE" ) title = f"GDD(base={gddbase:.0f},ceil={gddceil:.0f})" elif whichplots == "precip": fig = figure(apctx=ctx) - ax3 = fig.add_axes([0.1, 0.11, 0.8, 0.75]) + ax3 = fig.add_axes((0.1, 0.11, 0.8, 0.75)) ax1 = ax3 title = "Precipitation" else: # sdd fig = figure(apctx=ctx) - ax4 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) + ax4 = fig.add_axes((0.1, 0.1, 0.8, 0.8)) ax1 = ax4 title = "Stress Degree Days (base=86)" ax1.set_title( - (f"Accumulated {title}\n{station} {ctx['_nt'].sts[station]['name']}"), + f"Accumulated {title}\n{station} {ctx['_nt'].sts[station]['name']}", fontsize=18 if whichplots == "all" else 14, ) ab = ctx["_nt"].sts[station]["archive_begin"] if ab is None: raise NoDataFound("Unknown station metadata.") - for year in range(ab.year, datetime.datetime.now().year + 1): + for year in range(ab.year, datetime.now().year + 1): sts = sdate.replace(year=year) - ets = sts + datetime.timedelta(days=xlen - 1) + ets = sts + timedelta(days=xlen - 1) x = df.loc[sts:ets, f"o{glabel}"].cumsum() if x.empty: continue @@ -329,7 +329,7 @@ def plotter(ctx: dict): if now.day in wanted: xticks.append(i) xticklabels.append(now.strftime("%-d\n%b")) - now += datetime.timedelta(days=1) + now += timedelta(days=1) i += 1 if whichplots in ["all", "gdd"]: ax2.set_xticks(xticks) diff --git a/pylib/iemweb/autoplot/scripts100/p112.py b/pylib/iemweb/autoplot/scripts100/p112.py index 92c2f7ca6..f28b60991 100644 --- a/pylib/iemweb/autoplot/scripts100/p112.py +++ b/pylib/iemweb/autoplot/scripts100/p112.py @@ -3,7 +3,7 @@ month and year. """ -import datetime +from datetime import date import numpy as np import pandas as pd @@ -54,9 +54,9 @@ def modMonth( if ab is None: raise NoDataFound("Unknown station metadata.") s = ab.year - e = datetime.date(datetime.date.today().year + 1, 1, 1) + e = date(date.today().year + 1, 1, 1) for year in range(s, e.year): - now = datetime.date(year, 1, 1) + now = date(year, 1, 1) m1 = now.replace(month=mo1) m2 = now.replace(month=mo2) if m1 >= e or m1 not in db: @@ -139,9 +139,9 @@ def plotter(ctx: dict): # Site Information: [%s] %s # Contact Information: Daryl Herzmann akrherz@iastate.edu 515.294.5978 """ % ( - datetime.date.today().strftime("%d %b %Y"), + date.today().strftime("%d %b %Y"), bs, - datetime.date.today(), + date.today(), station, ctx["_nt"].sts[station]["name"], ) @@ -149,13 +149,11 @@ def plotter(ctx: dict): station, ) - monthly = [0] * 13 - for i in range(13): - monthly[i] = {"40": [], "48": [], "50": [], "XX": []} + monthly = [{"40": [], "48": [], "50": [], "XX": []}] * 13 db = {} for _, row in df.iterrows(): - ts = datetime.date(int(row["year"]), int(row["month"]), 1) + ts = date(int(row["year"]), int(row["month"]), 1) db[ts] = { "40": float(row["gdd40"]), "48": float(row["gdd48"]),