diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5af6d047..6aead08a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ Numbers in parentheses refer to GitHub issues and pull requests. Releases before
0.3.10 are described on the [GitHub Releases](https://github.com/cyberjunky/python-garminconnect/releases)
page.
+## [Unreleased]
+
+### Added
+
+- **The start and end of a night's sleep can be changed**: new `set_sleep_window(cdate, sleep_start, sleep_end)` moves when the sleep recorded for a day began and ended, like the web app's "Edit sleep" dialog on the Sleep page. It reads the day's sleep record with `GET sleep-service/sleep/dailySleep?date`, replaces the four start and end timestamps and sends the whole record back with `PUT sleep-service/sleep/dailySleep/{id}`, the URL and method the web app uses. Start and end must be timezone-aware datetimes, so a night is never shifted by guessing the timezone; the method returns the record read back after the write and raises `ValueError` when the day has no sleep record. (#484)
+
## [0.3.20] - 2026-10-23
### Added
diff --git a/README.md b/README.md
index 25ed2333..e3f40c23 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@
The Garmin Connect API library comes with two examples:
- **`example.py`** - Simple getting-started example showing authentication, token storage, and basic API calls
-- **`demo.py`** - Comprehensive demo providing access to **270 API methods** organized into **15 categories** for easy navigation
+- **`demo.py`** - Comprehensive demo providing access to **271 API methods** organized into **15 categories** for easy navigation
```bash
$ ./demo.py
@@ -51,11 +51,11 @@ Make your selection:
## API Coverage Statistics
-- **Total API Methods**: 348 methods; every method with a one-line description is listed in the [Method Reference](#-method-reference)
+- **Total API Methods**: 349 methods; every method with a one-line description is listed in the [Method Reference](#-method-reference)
- **Categories**: 15 organized sections
- **Web-app endpoint map**: the endpoints the Garmin Connect web app uses documented with the exact request it sends and whether it was verified live, in [docs/API_ENDPOINTS.md](docs/API_ENDPOINTS.md); the dashboard's GraphQL operations are in [docs/graphql_operations.md](docs/graphql_operations.md)
- **User & Profile**: 8 methods (basic user info, settings)
-- **Daily Health & Activity**: 21 methods (today's health data plus daily calories, resting HR and sleep ranges)
+- **Daily Health & Activity**: 22 methods (today's health data plus daily calories, resting HR and sleep ranges, editing when a night started and ended)
- **Advanced Health Metrics**: 35 methods (fitness metrics, HRV, VO2, FTP range, training readiness, training zones, running tolerance, training load balance, daily training status, activity training load)
- **Historical Data & Trends**: 29 methods (date range queries, weekly aggregates)
- **Activities & Workouts**: 37 methods (comprehensive activity, workout management, typed workout uploads including strength and swim CSS targets, in-place edit, scheduling, push to device, import, activity type/subtype filtering, earliest-upcoming-workout lookup, activity photos)
@@ -131,13 +131,13 @@ source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -e ".[example]"
python3 ./example.py # simple getting-started example
-python3 ./demo.py # comprehensive demo (270 API methods)
+python3 ./demo.py # comprehensive demo (271 API methods)
```
## 📚 Method Reference
-348 public methods on `Garmin`, generated from the code by `scripts/gen_method_reference.py`. Click a section to expand it.
+349 public methods on `Garmin`, generated from the code by `scripts/gen_method_reference.py`. Click a section to expand it.
Login, profile & account (21)
@@ -167,7 +167,7 @@ python3 ./demo.py # comprehensive demo (270 API methods)
-Daily health & wellness (75)
+Daily health & wellness (76)
| Method | Description |
| --- | --- |
@@ -244,6 +244,7 @@ python3 ./demo.py # comprehensive demo (270 API methods)
| `get_weekly_steps(end, weeks=52)` | Fetch weekly steps aggregates. |
| `get_weekly_stress(end, weeks=52)` | Fetch weekly stress aggregates. |
| `get_weekly_wellness_stats(start, end, metric_ids=None)` | Return weekly wellness metrics (default: resting heart rate, id 60). |
+| `set_sleep_window(cdate, sleep_start, sleep_end)` | Change when the night recorded for a day started and ended. |
| `set_steps_goal(steps, cdate=None)` | Set a manual daily step goal, or return to the device's automatic goal. |
| `update_jetlag_trip(trip_id, start_date, end_date, flights)` | Replace a Jet Lag Adviser trip. |
@@ -1042,7 +1043,7 @@ activity has photos attached.
### Additional Resources
- **Simple Example**: [example.py](https://raw.githubusercontent.com/cyberjunky/python-garminconnect/master/example.py) - Getting started guide
-- **Comprehensive Demo**: [demo.py](https://raw.githubusercontent.com/cyberjunky/python-garminconnect/master/demo.py) - All 270 API methods
+- **Comprehensive Demo**: [demo.py](https://raw.githubusercontent.com/cyberjunky/python-garminconnect/master/demo.py) - All 271 API methods
- **API Documentation**: Comprehensive method documentation in source code
- **Test Cases**: Real-world usage examples in `tests/` directory
diff --git a/demo.py b/demo.py
index 7178ff2f..9e4befa3 100755
--- a/demo.py
+++ b/demo.py
@@ -262,6 +262,10 @@ def month_start(self) -> datetime.date:
"key": "get_week_average_resting_hr",
},
"k": {"desc": "Fitness age details (v2)", "key": "get_fitness_age_details"},
+ "l": {
+ "desc": "Change sleep start and end of a night (interactive)",
+ "key": "set_sleep_window",
+ },
},
},
"3": {
@@ -5265,6 +5269,52 @@ def set_daily_goal_data(api: Garmin) -> None:
print(f"❌ Error setting goal: {e}")
+def set_sleep_window_data(api: Garmin) -> None:
+ """Change when a night's sleep started and ended."""
+ try:
+ cdate = input(f"Sleep date, the day you woke up (default {_today()}): ")
+ cdate = cdate.strip() or _today()
+ dto = (api.get_daily_sleep(cdate) or {}).get("dailySleepDTO") or {}
+ tz = api.now().tzinfo
+ current = {}
+ for side in ("Start", "End"):
+ ms = dto.get(f"sleep{side}TimestampGMT")
+ if ms:
+ current[side] = datetime.datetime.fromtimestamp(ms / 1000, tz)
+ if len(current) < 2:
+ print(f"❌ No sleep recorded for {cdate}")
+ return
+ print(
+ f"Times are in {tz}. Current window: {current['Start']} - {current['End']}"
+ )
+ new = {}
+ for side in ("Start", "End"):
+ value = input(
+ f"New sleep {side.lower()} (YYYY-MM-DD HH:MM, Enter to keep): "
+ )
+ value = value.strip()
+ new[side] = (
+ datetime.datetime.strptime(value, "%Y-%m-%d %H:%M").replace(tzinfo=tz)
+ if value
+ else current[side]
+ )
+ if new == current:
+ print("Cancelled")
+ return
+ call_and_display(
+ api.set_sleep_window,
+ cdate,
+ new["Start"],
+ new["End"],
+ method_name="set_sleep_window",
+ api_call_desc=(
+ f"api.set_sleep_window('{cdate}', {new['Start']!r}, {new['End']!r})"
+ ),
+ )
+ except Exception as e:
+ print(f"❌ Error changing sleep window: {e}")
+
+
def calendar_note_data(api: Garmin) -> None:
"""Add a calendar note for today and optionally delete it again."""
try:
@@ -6005,6 +6055,7 @@ def execute_api_call(api: Garmin, key: str) -> None:
"delete_gear": lambda: delete_gear_data(api),
"set_steps_goal": lambda: set_steps_goal_data(api),
"set_daily_goal": lambda: set_daily_goal_data(api),
+ "set_sleep_window": lambda: set_sleep_window_data(api),
"calendar_note": lambda: calendar_note_data(api),
"update_blood_pressure": lambda: update_blood_pressure_note_data(api),
"set_primary_training_device": lambda: set_primary_training_device_data(
diff --git a/docs/API_ENDPOINTS.md b/docs/API_ENDPOINTS.md
index 4fe86ce3..4dd8da12 100644
--- a/docs/API_ENDPOINTS.md
+++ b/docs/API_ENDPOINTS.md
@@ -111,6 +111,7 @@ Not added: `/metrics-service/metrics/eventracetimeprojections/{eventId}/{d1}/{d2
| `get_weekly_activity_stats(start, end, group_by_activity_type=True)` | `GET /userstats-service/activities/weekly/{displayName}?fromWeekStartDate&untilWeekStartDate&grpActType` | | yes |
| `get_user_statistics()` | `GET /userstats-service/statistics/{displayName}` | Totals per activity type. | yes |
| `get_daily_sleep(cdate=None, non_sleep_buffer_minutes=60)` | `GET /sleep-service/sleep/dailySleepData?date[&nonSleepBufferMinutes]` | The Sleep page's current call; `get_sleep_data` keeps the wellness-service variant. | yes |
+| `set_sleep_window(cdate, sleep_start, sleep_end)` | `GET /sleep-service/sleep/dailySleep?date`, then `PUT /sleep-service/sleep/dailySleep/{id}` with the whole record | The web app's "Edit sleep" dialog. Only the four start/end timestamps change (`…GMT` in UTC milliseconds, `…Local` as the wall-clock time encoded as UTC); URL and method from the web app's code; the record is sent back with the four timestamps replaced. Garmin answers 200 with a JSON body and recalculates the night. Returns the record read back. | yes (end time moved with the same request; this method verified writing an unchanged window) |
| `get_naps(cdate=None, include_overlaps=True)` | `GET /sleep-service/sleep/naps/{date}?includeOverlaps` | | yes (empty) |
| `get_sleep_stats_weekly(end=None, weeks=52)` | `GET /sleep-service/stats/sleep/weekly/{end}/{weeks}` | | yes |
| `get_sleep_stats_overall(start, end)` | `GET /sleep-service/stats/sleep/overall/{start}/{end}` | | yes |
diff --git a/garminconnect/api/health.py b/garminconnect/api/health.py
index c9579b84..afec0b2e 100644
--- a/garminconnect/api/health.py
+++ b/garminconnect/api/health.py
@@ -3,7 +3,7 @@
import math
import numbers
import re
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from typing import Any
from ..exceptions import GarminConnectAuthenticationError, GarminConnectConnectionError
@@ -23,6 +23,9 @@
)
from .base import GarminBase
+_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=UTC)
+_EPOCH_NAIVE = datetime(1970, 1, 1)
+
class HealthMixin(GarminBase):
"""Daily health and wellness data: summaries, sleep, heart rate, stress, hydration, nutrition, Health Snapshot, ECG, jet lag."""
@@ -1037,6 +1040,58 @@ def get_daily_sleep(
logger.debug("Requesting daily sleep")
return self.connectapi(url, params=params)
+ def set_sleep_window(
+ self, cdate: str, sleep_start: datetime, sleep_end: datetime
+ ) -> dict[str, Any]:
+ """Change when the night recorded for a day started and ended.
+
+ ``cdate`` is the sleep's calendar date (the day you woke up), as in
+ :meth:`get_daily_sleep`. ``sleep_start`` and ``sleep_end`` must be
+ timezone-aware datetimes; the wall-clock time in their timezone is
+ what Garmin shows as the local sleep time. URL and method are the ones
+ the web app's "Edit sleep" dialog uses: the method reads the day's sleep
+ record with GET /sleep-service/sleep/dailySleep?date, replaces the
+ four timestamps (``sleepStartTimestampGMT``/``Local`` and
+ ``sleepEndTimestampGMT``/``Local``, epoch milliseconds; the local
+ ones are the wall-clock time encoded as if it were UTC) and sends the
+ whole record back with PUT /sleep-service/sleep/dailySleep/{id}.
+ Garmin recalculates the night (sleep time and stages) for the new window.
+ Returns the sleep record read back after the write. Raises
+ ``ValueError`` when the day has no sleep record.
+ """
+ cdate = _validate_date_format(cdate, "cdate")
+ for name, value in (("sleep_start", sleep_start), ("sleep_end", sleep_end)):
+ if not isinstance(value, datetime):
+ raise ValueError(f"{name} must be a datetime")
+ if value.tzinfo is None or value.utcoffset() is None:
+ raise ValueError(f"{name} must be timezone-aware")
+ if sleep_end <= sleep_start:
+ raise ValueError("sleep_end must be after sleep_start")
+
+ url = f"{self.garmin_connect_sleep_service_url}/sleep/dailySleep"
+ params = {"date": cdate}
+ current = self.connectapi(url, params=params)
+ if not isinstance(current, dict) or not current.get("id"):
+ raise ValueError(f"no sleep record found for {cdate}")
+ sleep_id = _coerce_positive_id(current["id"], "sleep id")
+
+ def gmt_ms(dt: datetime) -> int:
+ return (dt - _EPOCH_UTC) // timedelta(milliseconds=1)
+
+ def local_ms(dt: datetime) -> int:
+ return (dt.replace(tzinfo=None) - _EPOCH_NAIVE) // timedelta(milliseconds=1)
+
+ payload = {
+ **current,
+ "sleepStartTimestampGMT": gmt_ms(sleep_start),
+ "sleepEndTimestampGMT": gmt_ms(sleep_end),
+ "sleepStartTimestampLocal": local_ms(sleep_start),
+ "sleepEndTimestampLocal": local_ms(sleep_end),
+ }
+ logger.debug("Updating sleep window for %s", cdate)
+ self.client.put("connectapi", f"{url}/{sleep_id}", json=payload)
+ return self.connectapi(url, params=params)
+
def get_naps(
self, cdate: str | None = None, include_overlaps: bool = True
) -> list[dict[str, Any]]:
diff --git a/tests/test_web_endpoints.py b/tests/test_web_endpoints.py
index b21656d5..7d1d360b 100644
--- a/tests/test_web_endpoints.py
+++ b/tests/test_web_endpoints.py
@@ -5,7 +5,7 @@
compatibility with Garmin's undocumented API.
"""
-from datetime import date
+from datetime import date, datetime, timedelta, timezone
import pytest
@@ -404,6 +404,81 @@ def test_user_settings_merge_and_primary_device(writer, monkeypatch):
assert calls[-1][2]["json"] == {"deviceId": 123}
+def test_set_sleep_window(writer, monkeypatch):
+ g, calls = writer
+ record = {
+ "id": 1000001,
+ "calendarDate": "2026-01-15",
+ "sleepStartTimestampGMT": 1768428900000,
+ "sleepEndTimestampGMT": 1768455000000,
+ "sleepStartTimestampLocal": 1768432500000,
+ "sleepEndTimestampLocal": 1768458600000,
+ "sleepTimeSeconds": 26100,
+ "sleepWindowConfirmed": True,
+ "sleepWindowConfirmationType": "enhanced_confirmed_final",
+ }
+ original = dict(record)
+ reads = []
+
+ def fake_get(path, **kw):
+ reads.append((path, kw))
+ return record if len(reads) == 1 else {"id": 1000001, "read": "back"}
+
+ monkeypatch.setattr(g, "connectapi", fake_get)
+ cet = timezone(timedelta(hours=1))
+ out = g.set_sleep_window(
+ "2026-01-15",
+ datetime(2026, 1, 14, 23, 30, tzinfo=cet),
+ datetime(2026, 1, 15, 7, 0, tzinfo=cet),
+ )
+ assert reads[0] == (
+ "/sleep-service/sleep/dailySleep",
+ {"params": {"date": "2026-01-15"}},
+ )
+ method, url, kw = calls[-1]
+ assert (method, url) == ("PUT", "/sleep-service/sleep/dailySleep/1000001")
+ assert kw["json"] == original | {
+ "sleepStartTimestampGMT": 1768429800000, # 22:30 UTC
+ "sleepEndTimestampGMT": 1768456800000, # 06:00 UTC
+ "sleepStartTimestampLocal": 1768433400000, # 23:30 wall clock
+ "sleepEndTimestampLocal": 1768460400000, # 07:00 wall clock
+ }
+ assert record == original # the record that was read stays untouched
+ assert reads[1] == reads[0] # read back after the write
+ assert out == {"id": 1000001, "read": "back"}
+
+
+def test_set_sleep_window_rejects_bad_input(writer, monkeypatch):
+ g, calls = writer
+ cet = timezone(timedelta(hours=1))
+ start = datetime(2026, 1, 14, 23, 30, tzinfo=cet)
+ end = datetime(2026, 1, 15, 7, 0, tzinfo=cet)
+ monkeypatch.setattr(g, "connectapi", lambda path, **kw: {"id": 1})
+ bad_calls = [
+ ("15.01.2026", start, end),
+ ("2026-01-15", start.replace(tzinfo=None), end),
+ ("2026-01-15", start, end.replace(tzinfo=None)),
+ ("2026-01-15", "2026-01-14T23:30:00+01:00", end),
+ ("2026-01-15", end, start),
+ ("2026-01-15", start, start),
+ ]
+ for args in bad_calls:
+ with pytest.raises(ValueError):
+ g.set_sleep_window(*args)
+ for bad_record in (
+ {},
+ None,
+ {"calendarDate": "2026-01-15"},
+ {"id": 0},
+ {"id": 1.9},
+ {"id": "1/../2"},
+ ):
+ monkeypatch.setattr(g, "connectapi", lambda path, _r=bad_record, **kw: _r)
+ with pytest.raises(ValueError):
+ g.set_sleep_window("2026-01-15", start, end)
+ assert calls == []
+
+
def test_calendar_notes(writer):
g, calls = writer
g.create_calendar_note("2026-10-20", "Race day", "Easy jog in the morning")