#11 Calendar Arithmetic & Browser Automation with Selenium
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.
Overview of Modules and Key Libraries
Know which Python library supports each calendar and time task.
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.
Quick Self-Check
1. Which library handles timezone-specific calculations?
pytz.2. Which library helps determine the weekday for a date?
calendar.3. Which library manages date and time objects?
datetime.The datetime Library and System Time
Import the datetime class and fetch the current system time.
now() reads the clock of the machine running the script.
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)
YYYY-MM-DD HH:MM:SS.microsecondsExample from the notes:
2018-10-04 16:10:33.123456
Date and time order
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?
2. What does the alias dt refer to?
datetime, imported as dt.3. What comes immediately after seconds in the sequence?
Timezone Management with pytz
Use timezone identifiers to obtain the time for a specified region.
dt.now().
| Timezone | Offset stated in the notes |
|---|---|
| GMT | 0° longitude reference |
| IST | GMT +5:30 |
| Singapore Standard Time | GMT +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))
pytz.timezone('Identifier') creates a timezone object for
the specified identifier.
Quick Self-Check
1. Which attribute lists supported timezone names?
pytz.all_timezones.2. How do you obtain time for a selected timezone?
pytz.timezone('Identifier'), then call
dt.now(tz_obj).
3. How far ahead of IST is Singapore Standard Time?
The calendar Module and Weekday Calculations
Convert a date into a weekday index, then map the index to a name.
calendar.weekday(year, month, day) returns an integer from
0 to 6 for the weekday.
| Index | Weekday | Index | Weekday |
|---|---|---|---|
| 0 | Monday | 4 | Friday |
| 1 | Tuesday | 5 | Saturday |
| 2 | Wednesday | 6 | Sunday |
| 3 | Thursday |
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))
Quick Self-Check
1. What index represents Monday?
2. What weekday corresponds to index 6?
3. What does calendar.weekday(2018, 7, 6) return?
Leap Year Detection Algorithm
Distinguish century years from non-century years using modulo checks.
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?
year % 400 == 0).
2. Is 1900 a leap year under these rules?
3. Which condition is used for a non-century year?
Month Days and Valid Date Logic
Check a day against the number of days allowed for its month and year.
| Month group | Rule from the notes | Days |
|---|---|---|
| February, leap year | Special case | 29 |
| February, non-leap year | Special case | 28 |
| Months 1–7: odd months | January, March, May, July | 31 |
| Months 1–7: even months | April, June (February handled separately) | 30 |
| Months 8–12: even months | August, October, December | 31 |
| Months 8–12: odd months | September, November | 30 |
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
- Keep prompting until the year is at least 1970.
- Keep prompting until the month is between 1 and 12 inclusive.
-
Call
check_leap(year), then keep prompting for the date untilcheck_valid_date(...)returnsTrue.
dt > 0 and dt < 32 for a 31-day month.
Quick Self-Check
1. How many days can February have in a leap year?
2. What month range is used for the first month-pattern rule?
3. What should the input loop do if the date is invalid?
True.
Fundamentals of Browser Automation
Learn how Selenium scripts automate common browser actions.
Installation requirements
pip install selenium
| Browser | Driver named in the notes |
|---|---|
| Google Chrome | chromedriver |
| Mozilla Firefox | geckodriver |
| Apple Safari | Safari Driver |
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?
pip install selenium.2. Which driver is named for Firefox?
geckodriver.3. What does browser.get(URL) do?
Inspecting Pages and Locating Elements
Use the browser's Inspect tool to understand page structure and element attributes.
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.
| Locator | Syntax shown in notes | Purpose |
|---|---|---|
| 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')
.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?
find_element_by_id()
in the notes.
2. What tool reveals the DOM tree?
3. What does send_keys('download') do?
Explicit Waits in Selenium
Wait for a dynamic page element to appear before continuing.
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))
)
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?
2. Which class creates the wait object?
WebDriverWait.3. Which expected condition appears in the example?
EC.presence_of_element_located().
WhatsApp Web Automation Workflow
Review the sequence of browser setup, authentication, locating a chat, and sending a 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)
-
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
-
Driver initialization: Start Chrome and navigate to
web.whatsapp.com. - QR authentication: The user manually scans the QR code using their mobile device.
-
Find the contact: Use an XPath expression targeting a
spanwith a matchingtitle. - Open the chat: Click the located contact element.
- Find the input field: Use the class name shown in the notes.
-
Send messages: Use
send_keys()to enter text andKeys.ENTERto send it.
Quick Self-Check
1. What must the user do when the QR code appears?
2. Which XPath pattern is used to find a contact?
//span[contains(@title, "Contact Name")],
with the target name inserted.
3. What does Keys.ENTER represent?
Rapid Revision Flashcards
Use these short prompts for a final review before the exam.
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.
pip install selenium
WebDriverWait with expected_conditions.
//span[contains(@title, "Contact Name")]
Comments
Post a Comment