#11 Calendar Arithmetic & Browser Automation with Selenium

NPTEL Module 11 | Exam Quick Study Guide
NPTEL · The Joy of Computing with Python

Your Module 11 Exam Prep Starts Here

Revise calendar arithmetic and browser automation with concise notes, key rules, code examples, and quick self-check questions.

Calendar Arithmetic Python Concepts Selenium Automation
Study key: Definition / key term Formula / rule Example / code idea
01

Overview of Modules and Key Libraries

Know which Python library supports each calendar and time task.

Revision tip Remember the purpose of each library before memorising its function names.

datetime

Manages date and time objects, system clocks, and precision timestamps.

pytz

Manages timezone-specific calculations and worldwide geographical time-offset mapping.

calendar

Provides helper functions for weekday calculations, leap-year checks, and month metadata.

Key term A Python library provides functions and tools for a particular set of tasks.

Quick Self-Check

1. Which library handles timezone-specific calculations?
Answer: pytz.
2. Which library helps determine the weekday for a date?
Answer: calendar.
3. Which library manages date and time objects?
Answer: datetime.
02

The datetime Library and System Time

Import the datetime class and fetch the current system time.

Remember now() reads the clock of the machine running the script.
Definition The datetime package includes related classes such as date, time, and datetime.

Importing datetime

from datetime import datetime as dt

Fetching current system time

from datetime import datetime as dt

current_time = dt.now()
print(current_time)
Output pattern YYYY-MM-DD HH:MM:SS.microseconds
Example from the notes: 2018-10-04 16:10:33.123456

Date and time order

Remember the sequence Year → Month → Date → Hours → Minutes → Seconds → Microseconds

The notes describe database date representations as moving from larger units to smaller units, from year through microseconds.

Quick Self-Check

1. What does dt.now() return?
Answer: The current system date and time of the machine running the script.
2. What does the alias dt refer to?
Answer: datetime, imported as dt.
3. What comes immediately after seconds in the sequence?
Answer: Microseconds.
03

Timezone Management with pytz

Use timezone identifiers to obtain the time for a specified region.

Memory hook Create a timezone object first, then pass it to dt.now().
TimezoneOffset stated in the notes
GMT0° longitude reference
ISTGMT +5:30
Singapore Standard TimeGMT +8:00; 2.5 hours ahead of IST

List supported timezone identifiers

import pytz

print(len(pytz.all_timezones))  # approximately 591

pytz.all_timezones returns an alphabetically sorted list. The notes describe a count typically around 570–591, depending on the operating system or package version.

Get the current time in Singapore

from datetime import datetime as dt
import pytz

tz_singapore = pytz.timezone('Singapore')
singapore_time = dt.now(tz_singapore)
print(singapore_time)

Iterate through all supported timezones

from datetime import datetime as dt
import pytz

timezones = pytz.all_timezones
for i in range(len(timezones)):
    zone = timezones[i]
    tz_obj = pytz.timezone(zone)
    print("Current time at zone", zone, "is", dt.now(tz_obj))
Key term pytz.timezone('Identifier') creates a timezone object for the specified identifier.

Quick Self-Check

1. Which attribute lists supported timezone names?
Answer: pytz.all_timezones.
2. How do you obtain time for a selected timezone?
Answer: Create a timezone object using pytz.timezone('Identifier'), then call dt.now(tz_obj).
3. How far ahead of IST is Singapore Standard Time?
Answer: 2.5 hours, according to the notes.
04

The calendar Module and Weekday Calculations

Convert a date into a weekday index, then map the index to a name.

Exam tip The weekday index starts at zero, not one.
Function calendar.weekday(year, month, day) returns an integer from 0 to 6 for the weekday.
IndexWeekdayIndexWeekday
0Monday4Friday
1Tuesday5Saturday
2Wednesday6Sunday
3Thursday

Map an index to a weekday name

import calendar

def get_day_name(day_index):
    list_of_days = [
        'Monday', 'Tuesday', 'Wednesday', 'Thursday',
        'Friday', 'Saturday', 'Sunday'
    ]
    return list_of_days[day_index]

day_idx = calendar.weekday(2018, 7, 6)
print(get_day_name(day_idx))
Example For July 6, 2018, the index is 4, which maps to Friday. The source note's printed comment says Thursday, but its own index mapping makes index 3 Thursday and index 4 Friday.

Quick Self-Check

1. What index represents Monday?
Answer: 0.
2. What weekday corresponds to index 6?
Answer: Sunday.
3. What does calendar.weekday(2018, 7, 6) return?
Answer: 4, which maps to Friday using the index table.
05

Leap Year Detection Algorithm

Distinguish century years from non-century years using modulo checks.

Remember Century years use divisibility by 400; other years use divisibility by 4.
Rule Century year: If year % 100 == 0, it is a leap year only if year % 400 == 0.

Non-century year: If year % 100 != 0, it is a leap year if year % 4 == 0.

Century examples

2000 is a leap year. 1900 and 1800 are not leap years.

Non-century examples

2016 is a leap year. 2009 is not a leap year.

Algorithm implementation

def check_leap(year):
    if year % 100 == 0:
        if year % 400 == 0:
            return True
        else:
            return False
    else:
        if year % 4 == 0:
            return True
        else:
            return False

Quick Self-Check

1. What extra condition must a century year satisfy?
Answer: It must be divisible by 400 (year % 400 == 0).
2. Is 1900 a leap year under these rules?
Answer: No. It is divisible by 100 but not by 400.
3. Which condition is used for a non-century year?
Answer: It must be divisible by 4.
06

Month Days and Valid Date Logic

Check a day against the number of days allowed for its month and year.

Study tip Check February separately. Then apply the month-number pattern.
Month groupRule from the notesDays
February, leap yearSpecial case29
February, non-leap yearSpecial case28
Months 1–7: odd monthsJanuary, March, May, July31
Months 1–7: even monthsApril, June (February handled separately)30
Months 8–12: even monthsAugust, October, December31
Months 8–12: odd monthsSeptember, November30

Date validation function

The function receives a day, month, year, and Boolean leap-year status. It returns True if the day is within the allowed range and False otherwise.

def check_valid_date(dt, month, year, l):
    # l is True for leap year, False otherwise
    if l:
        if month == 2:
            return dt > 0 and dt < 30
    else:
        if month == 2:
            return dt > 0 and dt < 29

    if month < 8:
        if month % 2 == 1:
            return dt > 0 and dt < 32
        else:
            return dt > 0 and dt < 31
    else:
        if month % 2 == 0:
            return dt > 0 and dt < 32
        else:
            return dt > 0 and dt < 31

Input validation loops

  1. Keep prompting until the year is at least 1970.
  2. Keep prompting until the month is between 1 and 12 inclusive.
  3. Call check_leap(year), then keep prompting for the date until check_valid_date(...) returns True.
Range reminder Valid day ranges in the function are expressed using conditions such as dt > 0 and dt < 32 for a 31-day month.

Quick Self-Check

1. How many days can February have in a leap year?
Answer: 29 days.
2. What month range is used for the first month-pattern rule?
Answer: Months 1 through 7.
3. What should the input loop do if the date is invalid?
Answer: Prompt again until the date validation function returns True.
07

Fundamentals of Browser Automation

Learn how Selenium scripts automate common browser actions.

Remember Selenium controls browser actions through code, rather than requiring each action to be performed manually.
Definition Browser automation uses scripts to open websites, navigate links, fill text boxes, click buttons, and retrieve data.

Installation requirements

pip install selenium
BrowserDriver named in the notes
Google Chromechromedriver
Mozilla Firefoxgeckodriver
Apple SafariSafari Driver
Key term A WebDriver executable bridges Selenium scripts and the target browser.

Initialize a browser and navigate

from selenium import webdriver

driver_path = '/Users/user/Downloads/chromedriver-2'
browser = webdriver.Chrome(driver_path)
browser.get('https://www.seleniumhq.org')

The path is an example from the notes. Driver setup syntax and compatibility can depend on the Selenium version in use.

Quick Self-Check

1. What command installs Selenium using pip?
Answer: pip install selenium.
2. Which driver is named for Firefox?
Answer: geckodriver.
3. What does browser.get(URL) do?
Answer: It navigates the browser to the specified URL.
08

Inspecting Pages and Locating Elements

Use the browser's Inspect tool to understand page structure and element attributes.

Exam tip Choose a locator based on the element information available in the page.
Key term The Document Object Model (DOM) represents the page structure, including HTML tags such as header, div, span, and input, with attributes such as id, class, title, and name.

Right-click or double-click a page element and select Inspect or Inspect Element to open Developer Tools.

LocatorSyntax shown in notesPurpose
Link text find_element_by_link_text('Downloads') Finds an anchor matching exact, case-sensitive text.
Element ID find_element_by_id('q') Finds an element by its ID attribute.
Class name find_element_by_class_name('_1Plpp') Finds elements by the class attribute.
XPath find_element_by_xpath('//span[...]') Locates elements using an XPath expression.

Click a link and type in a search field

elem_download = browser.find_element_by_link_text('Downloads')
elem_download.click()

search_box = browser.find_element_by_id('q')
search_box.send_keys('download')
Code idea .click() clicks the located element. .send_keys() sends text or key presses to it.

The locator method names above are reproduced from the notes and may be version-specific in modern Selenium.

Quick Self-Check

1. Which locator is used for a unique ID attribute?
Answer: The ID locator, shown as find_element_by_id() in the notes.
2. What tool reveals the DOM tree?
Answer: The browser's Inspect / Developer Tools feature.
3. What does send_keys('download') do?
Answer: It types or sends the text “download” to the selected field.
09

Explicit Waits in Selenium

Wait for a dynamic page element to appear before continuing.

Remember Explicit waits help when web content loads asynchronously.
Definition An explicit wait pauses script execution until a specified DOM condition is met or the timeout expires.

Imports

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

Wait for an element to be present

wait = WebDriverWait(driver, 600)

target_element = wait.until(
    EC.presence_of_element_located((By.XPATH, x_argument))
)
Remember the pattern WebDriverWait(driver, timeout).until(condition)

The notes use 600 as the timeout value and XPath as the locator strategy in this example.

Quick Self-Check

1. Why are explicit waits useful?
Answer: Web content may load asynchronously, so the script can wait until the required element appears.
2. Which class creates the wait object?
Answer: WebDriverWait.
3. Which expected condition appears in the example?
Answer: EC.presence_of_element_located().
10

WhatsApp Web Automation Workflow

Review the sequence of browser setup, authentication, locating a chat, and sending a message.

Study the sequence Initialize → Open WhatsApp Web → Wait for login/contact element → Select chat → Locate input → Send message.

Workflow code from the notes

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome('/Users/simran/Downloads/chromedriver-2')
driver.get('https://web.whatsapp.com')

wait = WebDriverWait(driver, 600)
target = 'Ravi kiran'
string = 'Message sent using Python'

x_arg = '//span[contains(@title, "' + target + '")]'
target_element = wait.until(
    EC.presence_of_element_located((By.XPATH, x_arg))
)
target_element.click()

input_box = driver.find_element_by_class_name('_1Plpp')
for i in range(50):
    input_box.send_keys(string)
    input_box.send_keys(Keys.ENTER)
Key terms
  • Keys.ENTER: Selenium key constant for the Enter key.
  • //span[contains(@title, "Contact Name")]: XPath pattern used in the notes to locate a span whose title contains a contact name.
  • WebDriverWait: waits for a required element condition.

Step-by-step breakdown

  1. Driver initialization: Start Chrome and navigate to web.whatsapp.com.
  2. QR authentication: The user manually scans the QR code using their mobile device.
  3. Find the contact: Use an XPath expression targeting a span with a matching title.
  4. Open the chat: Click the located contact element.
  5. Find the input field: Use the class name shown in the notes.
  6. Send messages: Use send_keys() to enter text and Keys.ENTER to send it.
Practical note The source example loops 50 times and sends the same message each time. Use automation responsibly and only send messages when you have permission. Web app class names can change.

Quick Self-Check

1. What must the user do when the QR code appears?
Answer: Manually scan it using their mobile device.
2. Which XPath pattern is used to find a contact?
Answer: //span[contains(@title, "Contact Name")], with the target name inserted.
3. What does Keys.ENTER represent?
Answer: The Enter key, used in the example to transmit the message.
↻

Rapid Revision Flashcards

Use these short prompts for a final review before the exam.

Final revision Try to say each answer aloud before reading it.
dt.now() Returns the current system timestamp.
pytz.all_timezones Lists supported timezone names alphabetically.
calendar.weekday(Y,M,D) Returns 0 for Monday through 6 for Sunday.
Century leap year Must be divisible by 400.
Non-century leap year Must be divisible by 4.
Selenium installation pip install selenium
WebDriver Connects Selenium code to a browser.
Inspect Element Shows DOM structure and element attributes.
Explicit wait WebDriverWait with expected_conditions.
WhatsApp XPath pattern //span[contains(@title, "Contact Name")]

One concept at a time. One question at a time. You are making progress.

Review the rules, practise the code patterns, and test your understanding.

↑ Back to top

Comments

Popular posts from this blog

#12 Page Rank & Collatz Conjuncture

#10 NumPy, Flames, Digital images & compression