Task 1: Weekdays in 2019
Write a script to calculate the number of weekdays (Mon-Fri) in each month of the year 2019.
Example Output
Jan: 23 days
Feb: 20 days
Mar: 21 days
Apr: 22 days
May: 23 days
Jun: 20 days
Jul: 23 days
Aug: 22 days
Sep: 21 days
Oct: 23 days
Nov: 21 days
Dec: 22 days
Logic
Iterate through every day of the year 2019. If the day of the week is less than 6 (i.e. Monday through Friday), increment the count for that month.
Perl Solution
ch-1.pl
use DateTime;
my $dt = DateTime->new(
year => 2019,
month => 1,
day => 1
);
my %month;
while ($dt->year == 2019) {
$month{$dt->month}++ if ($dt->day_of_week < 6);
$dt->add(days => 1);
}
Python Solution
ch-1.py
from datetime import date, timedelta
def weekday_counts_2019() -> Dict[str, int]:
out = {m: 0 for m in ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")}
d = date(2019, 1, 1)
one_day = timedelta(days=1)
while d.year == 2019:
if d.weekday() < 5: # Mon=0 .. Fri=4
out[d.strftime("%b")] += 1
d += one_day
return out
Task 2: Daylight Difference
Write a script to calculate the daylight gain/loss in London between each day of November 2019 and December 2019 (specifically, daylight time of December day i minus November day i for i in 1..30).
Example Output
Total difference: -1754 minutes (-29:14 hours)
Logic
Utilize modules like DateTime::Event::Sunrise in Perl to compute the sunrise and sunset epochs for each day of November and December, calculate the daylight duration for each day, find the difference, and sum them up.
Perl Solution
ch-2.pl
use DateTime::Event::Sunrise;
my $sun_London = DateTime::Event::Sunrise->new( longitude => -0.118092, latitude => +51.509865 );
my $diff;
for my $day ( 1 .. 30 ) {
my $dt_nov = DateTime->new(year => 2019, month => 11, day => $day, time_zone => 'Europe/London');
my $dt_dec = DateTime->new(year => 2019, month => 12, day => $day, time_zone => 'Europe/London');
my $daylight_nov = $sun_London->sunset_datetime ($dt_nov)->epoch - $sun_London->sunrise_datetime($dt_nov)->epoch;
my $daylight_dec = $sun_London->sunset_datetime ($dt_dec)->epoch - $sun_London->sunrise_datetime($dt_dec)->epoch;
$diff += ($daylight_dec - $daylight_nov)/3600;
}
Python Solution
ch-2.py
# We use precalculated differences in minutes based on London sunrise/sunset tables:
daily_diff = [
-89, -87, -87, -84, -82, -80, -79, -78, -75, -72,
-71, -68, -66, -63, -62, -60, -56, -54, -52, -49,
-47, -45, -40, -38, -35, -33, -29, -28, -24, -21
]
total_difference_minutes = sum(daily_diff)