{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a9331237",
   "metadata": {},
   "source": [
    "# Lecture 19 - I/O 2: Working with time\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "It's about time to wrap up the semester and to wrap up the semester, it's about time. Today, we'll look at how to represent dates and times in a program, calculate durations, and measure how long code takes to run. We'll then introduce asynchronous programming, which lets a program do other work while it waits. Finally, we'll bring these ideas together by reading structured data in JSON format.\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- representing dates and times with the `datetime` module;\n",
    "- calculating durations and comparing times from different time zones;\n",
    "- converting between dates and strings;\n",
    "- measuring elapsed time with the `time` module;\n",
    "- using `async`, `await`, and `asyncio.gather()` to write asynchronous code; and\n",
    "- reading JSON data and working with the timestamps it contains.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Official Python documentation: [Basic date and time types](https://docs.python.org/3/library/datetime.html), [Time access and conversions](https://docs.python.org/3/library/time.html), [Coroutines and tasks](https://docs.python.org/3/library/asyncio-task.html), and [JSON](https://docs.python.org/3/library/json.html).\n",
    "- W3Schools: [Datetime](https://www.w3schools.com/python/python_datetime.asp) and [JSON](https://www.w3schools.com/python/python_json.asp).\n",
    "- Helsinki Python MOOC: [Times and dates](https://programming-26.mooc.fi/part-7/3-times-and-dates) and [Data processing](https://programming-26.mooc.fi/part-7/4-data-processing)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aedda429",
   "metadata": {},
   "source": [
    "## 1. Working with dates and times"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79e9aec7",
   "metadata": {},
   "source": [
    "Working with dates can quickly become both complex, for example when handling different time zones or notations, and repetitive, as many pieces of code need relatively similar date-related operations. Fortunately, the `datetime` module in Python's standard library can handle a lot of the work for us.\n",
    "\n",
    "Two of its common classes include:\n",
    "\n",
    "- `date`, which stores a year, month, and day; and\n",
    "- `datetime` which stores a date *and* a time of day.\n",
    "\n",
    "Yes, confusingly, `datetime` is both the name of the module as well as the name of one of the classes within it.\n",
    "\n",
    "**Predict:** What will each line print? Which parts of the date and time can you access as attributes?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bd25a68",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import date, datetime\n",
    "\n",
    "lecture_date = date(2026, 11, 23)\n",
    "lecture_start = datetime(2026, 11, 23, 16, 10)\n",
    "\n",
    "print(lecture_date)\n",
    "print(lecture_start)\n",
    "print(lecture_start.year, lecture_start.month, lecture_start.day)\n",
    "print(lecture_start.hour, lecture_start.minute)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0fca92b",
   "metadata": {},
   "source": [
    "The arguments go from the largest unit to the smallest: year, month, day, hour, minute, and second. If we use `datetime` but leave out the time arguments, they default to zero. Python also checks that the date is possible - for example, trying to create 30 February raises a `ValueError`.\n",
    "\n",
    "Using these types to store dates and times is a lot more convenient than processing them as strings or numbers, especially when calculating durations, as we'll do below. Both classes also have convenient methods for accessing the local time of the system that is running the program:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52f7c613",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(date.today())\n",
    "print(datetime.now())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3add812",
   "metadata": {},
   "source": [
    "### Calculating durations\n",
    "\n",
    "The `timedelta` class allows us to represent a duration in any unit of time we'd like. It is named `timedelta` as the Greek letter *delta*, δ, is often used to represent differences.\n",
    "\n",
    "We can add or subtract a duration to a date or time and Python takes care of moving to the next day, month, or year where needed.\n",
    "\n",
    "**Predict:** When will the lecture finish? What will the date of next week's lecture be?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e4ce8ba9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import timedelta\n",
    "\n",
    "lecture_length = timedelta(minutes=50)\n",
    "lecture_end = lecture_start + lecture_length\n",
    "next_lecture = lecture_date + timedelta(weeks=1)\n",
    "\n",
    "print(lecture_end)\n",
    "print(next_lecture)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fafbbb4",
   "metadata": {},
   "source": [
    "Subtracting two dates or two datetimes works in the other direction: it gives us a `timedelta`. Its `.total_seconds()` method returns the duration in seconds, which we can divide by 60 to get minutes, or by 3600 to get hours."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26d6727e",
   "metadata": {},
   "outputs": [],
   "source": [
    "start = datetime(2026, 11, 23, 16, 10)\n",
    "end = datetime(2026, 11, 24, 11, 30)\n",
    "duration = end - start\n",
    "\n",
    "print(duration)\n",
    "print(duration.total_seconds() / 3600, \"hours\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b76d7642",
   "metadata": {},
   "source": [
    "We can also compare dates and times using the usual comparison operators, to see which one is earlier and which is later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cfbc8949",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(end > start)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7971dff2",
   "metadata": {},
   "source": [
    "### Converting between dates and strings\n",
    "\n",
    "Reading files or user input will usually give you dates as strings. To calculate with them, we'd then first need to turn those strings into date or datetime objects. This process, reading text according to a specific format to obtain values a program can work with, is called **parsing**.\n",
    "\n",
    "One commonly used way to write dates is the **ISO 8601** notation: year, month, day, then `T`, and then the time. For example, `2026-11-23T16:10:00` means 23 November 2026 at 16:10.\n",
    "\n",
    "The **ISO** is the *International Organization for Standardization*, a collaboration between the standards bodies of many standards organisations across the globe. They define many standards for things, from dates to country codes to even tea brewing (ISO 3103)!\n",
    "\n",
    "Anyway, if you ever come across strings formatted this way, `datetime.fromisoformat()` will read it. Vice versa, the `.isoformat()` method turns a datetime object back into a string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8fcfcc2",
   "metadata": {},
   "outputs": [],
   "source": [
    "timestamp_text = \"2026-11-23T16:10:00\"\n",
    "timestamp = datetime.fromisoformat(timestamp_text)\n",
    "\n",
    "print(type(timestamp_text))\n",
    "print(type(timestamp))\n",
    "print(timestamp + timedelta(minutes=50))\n",
    "print(timestamp.isoformat())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d376ed8",
   "metadata": {},
   "source": [
    "Adhering to standards is useful because we and our collaborators will always know what to expect. If we get the date in a different format, we'll need to specify to Python what the format actually is. For example, a date such as `\"03/04/2026\"` could mean 3 April or 4 March, depending on who wrote it.\n",
    "\n",
    "`datetime.strptime(text, format)` parses a string using a format that you specify. A datetime's `.strftime(format)` method uses the same format codes to produce a string for display. Read carefully - these methods only differ in one letter! `.strptime` stands for *string parse time* and `.strftime()` stands for *string format time*.\n",
    "\n",
    "The format is specified with the following codes:\n",
    "\n",
    "| Code | Meaning | Example |\n",
    "| --- | --- | --- |\n",
    "| `%Y` | Four-digit year | `2026` |\n",
    "| `%m` | Month number | `11` |\n",
    "| `%d` | Day of the month | `23` |\n",
    "| `%B` | Month name | `November` |\n",
    "| `%H` | Hour, using the 24-hour clock | `16` |\n",
    "| `%M` | Minute | `10` |\n",
    "| `%S` | Second | `00` |\n",
    "\n",
    "Note the difference between `%m` and `%M`: capitalisation matters! Which month name you get, depends on the language settings of the computer running Python.\n",
    "\n",
    "While the `datetime` module is specific to Python, these date formatting codes are used in multiple languages (such as C and PHP) as well as common libraries for other languages (such as JavaScript).\n",
    "\n",
    "**Predict:** Which date does the next cell read? What would change if we swapped `%d` and `%m` in the input format?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f2ba147",
   "metadata": {},
   "outputs": [],
   "source": [
    "appointment = datetime.strptime(\"03/04/2026 09:30\", \"%d/%m/%Y %H:%M\")\n",
    "print(appointment.strftime(\"%d %B %Y at %H:%M\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9686c41",
   "metadata": {},
   "source": [
    "These are the most commonly-used ones; there are a lot more, but you do not need to know any of them by heart. Do know that they exist, however, so you can recognise them when you come across them. If the text doesn't match the format, or the date is impossible, parsing raises a `ValueError`.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: crossing into a new year</b>\n",
    "\n",
    "A bus leaves at `\"31/12/2026 23:40\"` and the journey takes 50 minutes. Parse the departure time, calculate the arrival time, and print it in the format `\"01/01/2027 at 00:30\"`. Then subtract the departure time from the arrival time to check the journey length in minutes.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bb89693",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your solution here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73187073",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "departure = datetime.strptime(\"31/12/2026 23:40\", \"%d/%m/%Y %H:%M\")\n",
    "arrival = departure + timedelta(minutes=50)\n",
    "print(arrival.strftime(\"%d/%m/%Y at %H:%M\"))\n",
    "print((arrival - departure).total_seconds() / 60, \"minutes\")\n",
    "```\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a4298082",
   "metadata": {},
   "source": [
    "### Time zones\n",
    "\n",
    "There is one more thing to consider when a program deals with times: it's everyones favourite, **time zones**!\n",
    "\n",
    "Thankfully, the `datetime` library also has a `timezone` class built in.\n",
    "\n",
    "Computers use **UTC** (Coordinated Universal Time) as a common reference. UTC is what we call the time in the GMT (Greenwhich Mean Time) timezone. In the UK, it is GMT during winter, and BST (British Summer Time) in the summer.\n",
    "\n",
    "The **offset** says how far a clock is ahead of or behind UTC. In an ISO timestamp, `+00:00` means UTC, while `+01:00` means one hour ahead of UTC. GMT is UTC+0 and BST is UTC+1. \n",
    "\n",
    "A `datetime` that has timezone information included is called **aware**. By contrast, datetimes without any timezone information are called **naive**. When taking measurements from different places, using aware datetimes lets us compare the actual moments they represent.\n",
    "\n",
    "**Predict:** Will these two datetimes compare as equal?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fcb4db85",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import timezone\n",
    "\n",
    "edinburgh_time = datetime.fromisoformat(\"2026-11-23T09:00:00+00:00\")\n",
    "amsterdam_time = datetime.fromisoformat(\"2026-11-23T10:00:00+01:00\")\n",
    "\n",
    "print(edinburgh_time == amsterdam_time)\n",
    "print(amsterdam_time.astimezone(timezone.utc))\n",
    "print(datetime.now(timezone.utc))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1635b549",
   "metadata": {},
   "source": [
    "They are equal! `.astimezone()` converts a datetime to a particular timezone, such as `timezone.utc`.\n",
    "\n",
    "Use timezone information consistently: Python cannot compare a naive timezone to an aware one because it doesn't know which timezone the naive value belongs to.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: how long was the event?</b>\n",
    "\n",
    "An online event started at 9:15 AM UTC+0 on 27 May 2021 and ended at noon UTC+1 on the same day. Express both timestamps in ISO 8601, parse them both in UTC, and calculate the duration in minutes.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7853224",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your solution here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "070cac6e",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "event_start = datetime.fromisoformat(\"2021-05-27T09:15:00+00:00\")\n",
    "event_end = datetime.fromisoformat(\"2021-05-27T12:00:00+01:00\")\n",
    "event_start = event_start.astimezone(timezone.utc)\n",
    "event_end = event_end.astimezone(timezone.utc)\n",
    "print((event_end - event_start).total_seconds() / 60, \"minutes\")\n",
    "```\n",
    "\n",
    "The event lasts 105 minutes. The end time is 11:00 in UTC.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c055c4dc",
   "metadata": {},
   "source": [
    "### Measuring elapsed time\n",
    "\n",
    "Sometimes you'll want to know how long a piece of code takes to run, for example, when comparing the efficiency of two algorithms. For this, Python's `time` module (different from `datetime`!) provides `perf_counter()`. Call it before and after the code you want to measure and then subtract the two readings to get the elapsed time in seconds.\n",
    "\n",
    "This clock is designed for measuring durations and doesn't jump when the computer's calendar clock is corrected. Its readings don't represent datestimes, only the difference between them is useful\n",
    "\n",
    "The `time.sleep(seconds)` function pauses the current thread of execution, allowing you to make your code wait for a specified amount of time.\n",
    "\n",
    "**Predict:** Roughly how much time should pass between the two clock readings?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b12ccc1c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "before = time.perf_counter()\n",
    "time.sleep(0.2)\n",
    "elapsed = time.perf_counter() - before\n",
    "\n",
    "print(f\"Elapsed time: {elapsed:.3f} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87afc00b",
   "metadata": {},
   "source": [
    "You should see about 0.2 seconds. It may take a little longer, since your computer is doing other work in the background too."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5329b3fd",
   "metadata": {},
   "source": [
    "## 2. Asynchronicity"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9db51a8",
   "metadata": {},
   "source": [
    "Until now, our programs have all run **synchronously**: doing one thing after another. However, this is not always possible. For example, when working with data, you might need to wait for a file to finish processing or to be downloaded from the internet, without knowing how long that's going to happen. Or when working with hardware, you might need to wait for sensory input, or control several motors at the same time.\n",
    "\n",
    "**Concurrency** is the practice of programming several operations to be in progress at the same time. There are different ways to approach concurrency; here, we will look at **asynchronous programming**, where we allow Python to wait until something has finished and pick up later. There is also **parallelism**, where different strands of code actually execute at the same time, for example on different processor cores. Parallelism is beyond the scope of this course, however."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b17b6ac1",
   "metadata": {},
   "source": [
    "### Waiting with `async` and `await`\n",
    "\n",
    "Asynchronous programming in Python is handled by the `asyncio` library, short for *asynchronous input/output*. To simulate waiting for input, for example readings from the internet, we'll use the `asyncio.sleep()` function.\n",
    "\n",
    "`time.sleep()`, which we saw above, is a *synchronous* function. Like every other function we have seen so far in this course, it needs to be finished before the code that comes after it can run.\n",
    "\n",
    "By contrast, `asyncio.sleep()` is an *asynchronous function*, also known as a **coroutine**. This is a function that can pause while waiting for something."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2bccc5c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import asyncio\n",
    "\n",
    "print(\"Starting\")\n",
    "time.sleep(2)\n",
    "print(\"Checkpoint 1\")\n",
    "asyncio.sleep(2)\n",
    "print(\"Checkpoint 2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdd79419",
   "metadata": {},
   "source": [
    "As you can see, while the above code is allowed to run, it gives us a `RuntimeWarning: coroutine 'sleep' was never awaited`. While `time.sleep()` makes us wait two seconds before the code can continue, `asyncio.sleep()` lets other code go first and only executes after that. In the above piece of code, that means that `asyncio.sleep()` has essentially no impact on the running of the code, hence the warning.\n",
    "\n",
    "If we want to wait for a coroutine to finish, we have to use the `await` keyword:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acc67fa2",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Starting\")\n",
    "time.sleep(2)\n",
    "print(\"Checkpoint 1\")\n",
    "await asyncio.sleep(2)\n",
    "print(\"Checkpoint 2\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdb11fb3",
   "metadata": {},
   "source": [
    "We can make our own coroutines using the `async def` keywords. For example, here is a coroutine that emulates waiting for a reading from a weather station for a certain amount of time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45e4d7e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "async def wait_for_station(name, delay):\n",
    "    print(\"Requesting a reading from\", name)\n",
    "    await asyncio.sleep(delay)\n",
    "    print(\"Received a reply from\", name)\n",
    "    return name\n",
    "\n",
    "result = await wait_for_station(\"Meadows\", 0.3)\n",
    "print(\"Result:\", result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a865491b",
   "metadata": {},
   "source": [
    "Most of this looks like an ordinary function: it takes arguments, runs some code, and returns a value.\n",
    "\n",
    "The difference is that it can pause at `await` and resume when the result is ready. Counterintuitively, calling a coroutine does *not* actually run its body - instead, it create a **coroutine object**. You can think of a coroutine object as a *promise* of future work (in fact, in some programming languages, they are literally called *Promises*). It is only when we use `await` that it is run and the value is returned.\n",
    "\n",
    "Asynchronous code has to be run inside of an **event loop**. Conveniently for us, Noteable already has an event loop built in, which means we have been able to `await` coroutines directly in our code. However, in regular Python scripts, you'll need to start your own event loops using `asyncio.run()`, like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba32da9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# This will throw an error in Noteable as you cannot run an event loop inside an event loop\n",
    "# Create a regular Python file or use the Python REPL to try this out\n",
    "asyncio.run(wait_for_station(\"Meadows\", 0.3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ae13da6c",
   "metadata": {},
   "source": [
    "Let's try running multiple coroutines at once.\n",
    "\n",
    "**Predict:** In the next cell, will the request to Leith start before Meadows replies? Roughly how long will the whole cell take?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b6912a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "before = time.perf_counter()\n",
    "\n",
    "first = await wait_for_station(\"Meadows\", 0.3)\n",
    "second = await wait_for_station(\"Leith\", 0.1)\n",
    "\n",
    "sequential_elapsed = time.perf_counter() - before\n",
    "print([first, second])\n",
    "print(f\"Time taken: {sequential_elapsed:.2f} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8faa1904",
   "metadata": {},
   "source": [
    "We still wait for Meadows to finish before requesting Leith. The two waits add up to about 0.4 seconds. While using `await` allows us to run asynchronous functions, the functions themselves are still executed one after the other. Can we make this more efficient?\n",
    "\n",
    "### Waiting for several things together\n",
    "\n",
    "To maximise the usefulness of asynchronous programming, `asyncio.gather()` schedules the coroutines we give it to run concurrently. Awaiting it then gives us a list of their results once they have all finished successfully.\n",
    "\n",
    "**Predict:** How long will the following piece of code take?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b55a55c",
   "metadata": {},
   "outputs": [],
   "source": [
    "before = time.perf_counter()\n",
    "\n",
    "station_names = await asyncio.gather(\n",
    "    wait_for_station(\"Meadows\", 0.3),\n",
    "    wait_for_station(\"Leith\", 0.1),\n",
    ")\n",
    "\n",
    "concurrent_elapsed = time.perf_counter() - before\n",
    "print(station_names)\n",
    "print(f\"Time taken: {concurrent_elapsed:.2f} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7e80a70",
   "metadata": {},
   "source": [
    "Now that the two waits overlap, the total is only about 0.3 seconds: roughly the longest wait! While a win of 0.1 seconds is not that much, imagine you are downloading several files multiple gigabytes in size. Being able to do this concurrently using asynchronous code will save you a lot of time!\n",
    "\n",
    "Note that even though Leith replies first, the results list is still `[\"Meadows\", \"Leith\"]`. `gather()` returns values in the order we supplied the coroutines, regardless of which finishes first.\n",
    "\n",
    "\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: a third station</b>\n",
    "\n",
    "Use `asyncio.gather()` to request Meadows, Leith, and Portobello, with delays of 0.3, 0.1, and 0.2 seconds respectively. Measure the elapsed time with `time.perf_counter()`. Before running the code, predict the order of the replies, the order of the returned names, and the approximate total time. How long would the waits take if we requested each station in turn instead?\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "119ccd4f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your solution here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce6f9436",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "before = time.perf_counter()\n",
    "names = await asyncio.gather(\n",
    "    wait_for_station(\"Meadows\", 0.3),\n",
    "    wait_for_station(\"Leith\", 0.1),\n",
    "    wait_for_station(\"Portobello\", 0.2),\n",
    ")\n",
    "print(names)\n",
    "print(f\"Time taken: {time.perf_counter() - before:.2f} seconds\")\n",
    "```\n",
    "\n",
    "The replies should arrive from Leith, Portobello, and Meadows, but the returned list is `[\"Meadows\", \"Leith\", \"Portobello\"]`. The waits overlap, taking about 0.3 seconds in total. Requesting each station in turn would take about 0.6 seconds. Actual timings will vary a little depending on your computer!\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0986cb18",
   "metadata": {},
   "source": [
    "## 3. Reading JSON data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd55e6d7",
   "metadata": {},
   "source": [
    "So far, our pretend weather stations have only returned their names. A real station would need to send more information: a temperature, the time it was measured, and perhaps several other readings.\n",
    "\n",
    "When requesting data, we usually do this through an **Application Programming Interface** or **API**, an endpoint through which a service gives us access to its data. On the internet, data is often formatted in **JSON** (JavaScript Object Notation), a text format for storing and exchanging structured data. Despite the name, this format is used by programs written in many languages, including Python.\n",
    "\n",
    "As its name suggests, a JSON file is structured as one large object, using JavaScript's notation:\n",
    "\n",
    "```JSON\n",
    "{\n",
    "    \"station\": \"Meadows\",\n",
    "    \"reading\": {\n",
    "        \"time\": \"2026-11-23T09:45:00+00:00\",\n",
    "        \"temperature_c\": 1.2\n",
    "    },\n",
    "    \"online\": true\n",
    "}\n",
    "```\n",
    "\n",
    "It should look fairly familiar - objects use braces and pairs of keys and values, while arrays (lists) use square brackets. The `json` module turns them into Pythonic types:\n",
    "\n",
    "| JSON | Python |\n",
    "| --- | --- |\n",
    "| Object | `dict` |\n",
    "| Array | `list` |\n",
    "| String | `str` |\n",
    "| Number | `int` or `float` |\n",
    "| `true` / `false` | `True` / `False` |\n",
    "| `null` | `None` |\n",
    "\n",
    "JSON strings and object keys *must* use double quotation marks.\n",
    "\n",
    "### Reading a JSON string\n",
    "\n",
    "`json.loads()` reads JSON from a string. Note the final `s`; it stands for *string*.\n",
    "\n",
    "**Predict:** What type will `observation` have? What about the temperature and timestamp inside it?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24979c3d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "sample_response = \"\"\"{\n",
    "    \"station\": \"Meadows\",\n",
    "    \"reading\": {\n",
    "        \"time\": \"2026-11-23T09:45:00+00:00\",\n",
    "        \"temperature_c\": 1.2\n",
    "    },\n",
    "    \"online\": true\n",
    "}\"\"\"\n",
    "\n",
    "observation = json.loads(sample_response)\n",
    "print(observation)\n",
    "print(type(observation))\n",
    "print(type(observation[\"reading\"][\"temperature_c\"]))\n",
    "print(type(observation[\"reading\"][\"time\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc098215",
   "metadata": {},
   "source": [
    "As you can see, `loads()` converts each part of the JSON file into the relevant base Python type.\n",
    "\n",
    "The timestamp, however, is still a string. As JSON has no separate date or time type, we need `datetime.fromisoformat()` before we can calculate with it.\n",
    "\n",
    "Let's find out how old this observation was when we prepared a report at 10:00 UTC on the same day.\n",
    "\n",
    "**Predict:** How many minutes old was the observation?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2daff8a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "report_time = datetime.fromisoformat(\"2026-11-23T10:00:00+00:00\")\n",
    "measured_at = datetime.fromisoformat(observation[\"reading\"][\"time\"])\n",
    "age = report_time - measured_at\n",
    "\n",
    "print(observation[\"station\"])\n",
    "print(observation[\"reading\"][\"temperature_c\"], \"°C\")\n",
    "print(age.total_seconds() / 60, \"minutes old\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc2aa310",
   "metadata": {},
   "source": [
    "### Reading a JSON file\n",
    "\n",
    "We can also read JSON directly from a file using `json.load()`, without the final `s`. As in Lecture 10, we open the file using `with` so that it closes when we're finished.\n",
    "\n",
    "The next cell first writes the above example text to a file, so we have something to read. We'll keep it in a `selfguided_output` folder using `Path`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "00633997",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "# Write an example JSON file\n",
    "data_dir = Path(\"selfguided_output\")\n",
    "data_dir.mkdir(exist_ok=True)\n",
    "json_path = data_dir / \"weather_observation.json\"\n",
    "\n",
    "with open(json_path, \"w\", encoding=\"utf-8\") as file:\n",
    "    file.write(sample_response)\n",
    "\n",
    "# Read and process the example JSON file\n",
    "with open(json_path, \"r\", encoding=\"utf-8\") as file:\n",
    "    saved_observation = json.load(file)\n",
    "\n",
    "print(saved_observation == observation)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3395ebc",
   "metadata": {},
   "source": [
    "The result is the same dictionary, whether the JSON came from a string or a file. If the text isn't valid JSON, these functions would raise a `json.JSONDecodeError`, which we can handle with `try` and `except`.\n",
    "\n",
    "### Bringing it all together\n",
    "\n",
    "Now let's collect three observations and compare their times. Below are two more example replies to go with `sample_response`. Note the UTC offset in Leith's timestamp!\n",
    "\n",
    "Our `receive_observation()` coroutine simulates waiting for a reply, before reading the JSON text into a dictionary. We're just pretending there is a network delay; `json.loads()` itself is a synchronous function and doesn't need `await`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28a6dfb9",
   "metadata": {},
   "outputs": [],
   "source": [
    "leith_response = \"\"\"{\n",
    "    \"station\": \"Leith\",\n",
    "    \"reading\": {\n",
    "        \"time\": \"2026-11-23T10:50:00+01:00\",\n",
    "        \"temperature_c\": 2.1\n",
    "    },\n",
    "    \"online\": true\n",
    "}\"\"\"\n",
    "\n",
    "portobello_response = \"\"\"{\n",
    "    \"station\": \"Portobello\",\n",
    "    \"reading\": {\n",
    "        \"time\": \"2026-11-23T09:40:00+00:00\",\n",
    "        \"temperature_c\": 2.6\n",
    "    },\n",
    "    \"online\": true\n",
    "}\"\"\"\n",
    "\n",
    "async def receive_observation(response_text, delay):\n",
    "    await asyncio.sleep(delay)\n",
    "    return json.loads(response_text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "635a371d",
   "metadata": {},
   "source": [
    "**Predict:** How long should collecting all three observations take? Which observation will be the most recent?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6692120b",
   "metadata": {},
   "outputs": [],
   "source": [
    "before = time.perf_counter()\n",
    "observations = await asyncio.gather(\n",
    "    receive_observation(sample_response, 0.5),\n",
    "    receive_observation(leith_response, 0.2),\n",
    "    receive_observation(portobello_response, 0.8),\n",
    ")\n",
    "collection_elapsed = time.perf_counter() - before\n",
    "\n",
    "for item in observations:\n",
    "    measured_at = datetime.fromisoformat(item[\"reading\"][\"time\"])\n",
    "    measured_at = measured_at.astimezone(timezone.utc)\n",
    "    temperature = item[\"reading\"][\"temperature_c\"]\n",
    "    print(f\"{item['station']}: {temperature}°C at {measured_at.strftime('%H:%M')} UTC\")\n",
    "\n",
    "print(f\"Collected the observations in {collection_elapsed:.2f} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1565c10",
   "metadata": {},
   "source": [
    "Collecting the observations should take about 0.8 seconds and Leith's reply arrives first.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: which readings need updating?</b>\n",
    "\n",
    "Write a coroutine called `observation_age(response_text, delay, reference_time)` that:\n",
    "\n",
    "1. Awaits `receive_observation()` to get the observation dictionary;\n",
    "2. Converts the measurement's timestamp into an aware datetime in UTC;\n",
    "3. Calculates how many minutes before `reference_time` the measurement was taken; and\n",
    "4. Returns a dictionary with the keys `\"station\"` and `\"age_minutes\"`.\n",
    "\n",
    "Run it for all three replies, using the same delays as above and `report_time` as the reference time. Print each station's age as well as an extra message for any reading that is more than 15 minutes old.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae1de834",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your solution here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1ef434e",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "You should get ages of 15, 10, and 20 minutes for Meadows, Leith, and Portobello respectively. Only Portobello needs updating under this rule.\n",
    "\n",
    "```python\n",
    "async def observation_age(response_text, delay, reference_time):\n",
    "    item = await receive_observation(response_text, delay)\n",
    "    measured_at = datetime.fromisoformat(item[\"reading\"][\"time\"])\n",
    "    measured_at = measured_at.astimezone(timezone.utc)\n",
    "    age_minutes = (reference_time - measured_at).total_seconds() / 60\n",
    "    return {\"station\": item[\"station\"], \"age_minutes\": age_minutes}\n",
    "\n",
    "ages = await asyncio.gather(\n",
    "    observation_age(sample_response, 0.5, report_time),\n",
    "    observation_age(leith_response, 0.2, report_time),\n",
    "    observation_age(portobello_response, 0.8, report_time),\n",
    ")\n",
    "\n",
    "for item in ages:\n",
    "    print(f\"{item['station']}: {item['age_minutes']:.0f} minutes old\")\n",
    "    if item[\"age_minutes\"] > 15:\n",
    "        print(\"Request a newer reading from\", item[\"station\"])\n",
    "```\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94781f9a",
   "metadata": {},
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "Let's finish up with the final consolidation challenge of the course!\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: plan an afternoon</b>\n",
    "\n",
    "The two JSON replies below describe events from different calendars. Can you attend both, and how much time will you have between them?\n",
    "\n",
    "1. Write a coroutine called `read_event(response_text, delay)`. It should wait using `asyncio.sleep(delay)`, read the JSON, and convert the start time into an aware datetime in UTC. Calculate the end time using the event's duration, then return a dictionary with the keys `\"name\"`, `\"start\"`, and `\"end\"`.\n",
    "2. Collect the careers talk first and the study group second, with simulated delays of 0.1 and 0.4 seconds respectively. Measure how long collecting both takes using `time.perf_counter()`.\n",
    "3. Sort the returned events by start time (refer to Lecture 17 if you forgot how!).\n",
    "4. Print each event's name, start time, and end time, formatting the times as hours and minutes in UTC.\n",
    "5. Calculate the gap between the first event's end and the second event's start, in minutes. Use assertions to check the event order and the gap.\n",
    "</div>\n",
    "\n",
    "Before running your code, work out the timetable and the gap yourself. Should the collection time be closer to 0.4 or 0.5 seconds? Does the first reply describe the first event in the afternoon?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a6ed6e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "talk_response = \"\"\"{\n",
    "    \"name\": \"Careers talk\",\n",
    "    \"start\": \"2023-06-02T16:00:00+01:00\",\n",
    "    \"duration_minutes\": 30\n",
    "}\"\"\"\n",
    "\n",
    "study_response = \"\"\"{\n",
    "    \"name\": \"Study group\",\n",
    "    \"start\": \"2023-06-02T14:00:00+00:00\",\n",
    "    \"duration_minutes\": 45\n",
    "}\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3784b025",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Your solution here!"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f60289e",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "async def read_event(response_text, delay):\n",
    "    await asyncio.sleep(delay)\n",
    "    event = json.loads(response_text)\n",
    "    start = datetime.fromisoformat(event[\"start\"]).astimezone(timezone.utc)\n",
    "    end = start + timedelta(minutes=event[\"duration_minutes\"])\n",
    "    return {\"name\": event[\"name\"], \"start\": start, \"end\": end}\n",
    "\n",
    "before = time.perf_counter()\n",
    "events = await asyncio.gather(\n",
    "    read_event(talk_response, 0.1),\n",
    "    read_event(study_response, 0.4),\n",
    ")\n",
    "elapsed = time.perf_counter() - before\n",
    "\n",
    "def start_time(event):\n",
    "    return event[\"start\"]\n",
    "\n",
    "ordered_events = sorted(events, key=start_time)\n",
    "for event in ordered_events:\n",
    "    start_text = event[\"start\"].strftime(\"%H:%M\")\n",
    "    end_text = event[\"end\"].strftime(\"%H:%M\")\n",
    "    print(f\"{event['name']}: {start_text} to {end_text} UTC\")\n",
    "\n",
    "gap = ordered_events[1][\"start\"] - ordered_events[0][\"end\"]\n",
    "gap_minutes = gap.total_seconds() / 60\n",
    "print(f\"Time between events: {gap_minutes:.0f} minutes\")\n",
    "print(f\"Collected the events in {elapsed:.2f} seconds\")\n",
    "\n",
    "assert [event[\"name\"] for event in ordered_events] == [\"Study group\", \"Careers talk\"]\n",
    "assert gap_minutes == 15\n",
    "```\n",
    "\n",
    "The study group runs from 14:00 to 14:45 UTC, and the careers talk from 15:00 to 15:30 UTC. They don't overlap, and there are 15 minutes between them.\n",
    "\n",
    "The replies take about 0.4 seconds to collect because the waits overlap. The careers talk's reply arrives first and is first in the list from `gather()`, but the study group starts earlier. Sorting the events puts them in timetable order.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e89d52b5",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "Well done! 🥳 If there's anything we've seen in this lecture, it's that time flies. How strange to be writing the final self-guided notebook of the semester already... Good luck with the final bits of the semester, and if you've made it all this way, do let us know what you thought of these notebooks and whether you have any feedback for us as it'd be greatly appreciated!\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "    <dt><b>Timestamp</b></dt>\n",
    "    <dd>A date and time recording when something happened.</dd>\n",
    "    <dt><b>Parsing</b></dt>\n",
    "    <dd>Reading text according to a format to obtain values a program can work with.</dd>\n",
    "    <dt><b>UTC</b></dt>\n",
    "    <dd>Coordinated Universal Time, a common reference for expressing times from different places.</dd>\n",
    "    <dt><b>UTC offset</b></dt>\n",
    "    <dd>How far a clock is ahead of or behind UTC at a particular moment.</dd>\n",
    "    <dt><b>Aware / naive datetime</b></dt>\n",
    "    <dd>An aware datetime has usable timezone information; a naive one does not.</dd>\n",
    "    <dt><b>Asynchronous programming</b></dt>\n",
    "    <dd>Organising work so that other operations can make progress while one operation is waiting.</dd>\n",
    "    <dt><b>Coroutine</b></dt>\n",
    "    <dd>An operation created by calling an <code>async def</code> function, which can pause and resume while awaiting results.</dd>\n",
    "    <dt><b>Event loop</b></dt>\n",
    "    <dd>The mechanism that organises asynchronous work and resumes it when awaited operations are ready.</dd>\n",
    "    <dt><b>JSON</b></dt>\n",
    "    <dd>A text format for storing and exchanging structured data, including objects, arrays, numbers, and strings.</dd>\n",
    "    <dt><b>Web API</b></dt>\n",
    "    <dd>An interface through which a program requests data or actions from a web service.</dd>\n",
    "</dl>\n",
    "\n",
    "### New syntax\n",
    "\n",
    "<dl>\n",
    "    <dt><code>time.perf_counter()</code></dt>\n",
    "    <dd>Reads a clock for measuring elapsed time by subtracting two readings.</dd>\n",
    "    <dt><code>time.sleep(seconds)</code></dt>\n",
    "    <dd>Pauses the current thread of execution until the timer finishes.</dd>\n",
    "    <dt><code>asyncio.sleep(seconds)</code></dt>\n",
    "    <dd>Provides a timer to await, allowing other asynchronous work to run during the wait.</dd>\n",
    "    <dt><code>async def name(...):</code></dt>\n",
    "    <dd>Defines a coroutine function, which can use <code>await</code>.</dd>\n",
    "    <dt><code>await operation</code></dt>\n",
    "    <dd>Waits for an asynchronous result, allowing other scheduled work to run if <code>operation</code> pauses.</dd>\n",
    "    <dt><code>await asyncio.gather(first, second)</code></dt>\n",
    "    <dd>Runs operations concurrently and, on success, gets their results in argument order.</dd>\n",
    "    <dt><code>json.loads(text)</code> / <code>json.load(file)</code></dt>\n",
    "    <dd>Reads JSON from a string or an open file into Python values.</dd>\n",
    "</dl>\n",
    "\n",
    "#### From the `datetime` module\n",
    "\n",
    "<dl>\n",
    "    <dt><code>date(year, month, day)</code></dt>\n",
    "    <dd>Creates a date. Use <code>date.today()</code> to get the current local date.</dd>\n",
    "    <dt><code>datetime(year, month, day, hour, minute)</code></dt>\n",
    "    <dd>Creates a date and time. Time arguments left out default to zero.</dd>\n",
    "    <dt><code>datetime.now()</code> / <code>datetime.now(timezone.utc)</code></dt>\n",
    "    <dd>Gets the current local date and time without timezone information, or an aware datetime in UTC.</dd>\n",
    "    <dt><code>timedelta(days=1, hours=2)</code></dt>\n",
    "    <dd>Represents a duration, which can be added to or subtracted from a datetime. Multiple time units are supported.</dd>\n",
    "    <dt><code>duration.total_seconds()</code></dt>\n",
    "    <dd>Get the whole duration of a timedelta in seconds, including any complete days.</dd>\n",
    "    <dt><code>datetime.fromisoformat(text)</code> / <code>timestamp.isoformat()</code></dt>\n",
    "    <dd>Convert an ISO timestamp to a datetime and a datetime back to an ISO string.</dd>\n",
    "    <dt><code>datetime.strptime(text, format)</code></dt>\n",
    "    <dd>Parse a date and time using a specified format, such as <code>\"%d/%m/%Y %H:%M\"</code>.</dd>\n",
    "    <dt><code>timestamp.strftime(format)</code></dt>\n",
    "    <dd>Format a date and time as a string using format codes.</dd>\n",
    "    <dt><code>timestamp.astimezone(timezone.utc)</code></dt>\n",
    "    <dd>Express an aware timestamp in UTC, keeping the same moment.</dd>\n",
    "</dl>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
