Per-notebook time zone configuration in Jupyter kernels
0 reputation · 06 Oct 2021, 00:53 UTC
0 reputation · 06 Oct 2021, 00:53 UTC
The goal is to ensure that date‑sensitive computations produce the same naive datetime values regardless of which regional server executes the notebook.
Currently, notebook metadata stores creation and modification timestamps as ISO 8601 strings (usually UTC), but kernels run in the host’s local time zone with no per‑notebook override; the only reliable way to change the kernel’s TZ is to set the environment variable before the kernel starts.
It is unclear whether a notebook can declare its intended time zone in a way that the kernel honors without modifying the kernel spec, or whether Jupyter Server could automatically inject that zone into the kernel environment based on notebook metadata.
34775 reputation · 06 Oct 2021, 06:54 UTC
There is no native mechanism in the Jupyter Notebook format or the Jupyter Server kernel manager to declare a time zone in notebook metadata that a kernel will automatically respect. The .ipynb metadata is used for UI state and versioning, but it is not passed as an environment configuration to the kernel process during launch.
kernel.json specification, which uses a static env map.kernel.json file applies the change to every notebook using that kernel, making it unsuitable for per-notebook overrides.Since the server cannot inject the time zone, you must handle it within the notebook execution context. Depending on your requirements for "naive" datetime consistency, use one of the following methods:
To shift the kernel's perception of the local time zone for the current session, set the TZ environment variable and call tzset(). This must be done at the start of the notebook.
import os
import time
os.environ['TZ'] = 'UTC'
time.tzset() # Required on Unix systems to update the C library timezone
To ensure computations are identical across regional servers without relying on system-level environment variables, avoid naive datetimes entirely. Use zoneinfo (Python 3.9+) to force a specific zone for all calculations.
from datetime import datetime
from zoneinfo import ZoneInfo
# Force UTC regardless of server location
now = datetime.now(ZoneInfo("UTC"))
To verify if a time zone change has successfully propagated to the kernel, execute the following in a cell:
import time
print(time.tzname) # Should reflect the target zone (e.g., 'UTC')
Diagnostic Note: Are you using a custom JupyterHub spawn hook or a specific kernel gateway (like Kubernetes)? If so, environment injection may be possible at the orchestrator level, though it remains outside the standard Jupyter specification.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.