string indices must be integers URL - python-3.x

I'm trying to get name and date of all the holidays but got this error "string indices must be integers"
import requests
import datetime
from datetime import date
url = 'https://api.alpha.ca.gov/StateHolidayCalendar/all'
resp = requests.get(url)
text = resp.text
print(text)
print('As of',date.today(), ', the remaining holidays in the US for this year are: ')
for h in text:
print ('holiday: ',h['name'], ' is on ',h['date'])
https://api.alpha.ca.gov/StateHolidayCalendar/all returns the following response:
[
{
"name": "New Year's Day",
"date": "2020-01-01T08:00:00.000Z"
},
{
"name": "Martin Luther King Jr. Day",
"date": "2020-01-20T08:00:00.000Z"
},
...
]

text is a string, hence h is a string, h['name'] and h['date'] make no sense at all.
You should parse the response using .json():
...
data = resp.json()
Then you can treat it as a list of dictionaries:
for holiday in data:
print(holiday['name'], holiday['date'])
will output
New Year's Day 2020-01-01T08:00:00.000Z
Martin Luther King Jr. Day 2020-01-20T08:00:00.000Z
Presidents' Day 2020-02-17T08:00:00.000Z
Cesar Chavez Day 2020-03-31T08:00:00.000Z
Memorial Day 2020-05-25T08:00:00.000Z
Independence Day 2020-07-04T08:00:00.000Z
Labor Day 2020-09-07T08:00:00.000Z
Veterans Day 2020-11-11T08:00:00.000Z
Thanksgiving Day 2020-11-26T08:00:00.000Z
Day after Thanksgiving 2020-11-27T08:00:00.000Z
Christmas Day 2020-12-25T08:00:00.000Z
New Year's Day 2021-01-01T08:00:00.000Z
Martin Luther King Jr. Day 2021-01-18T08:00:00.000Z
Presidents' Day 2021-02-15T08:00:00.000Z
Cesar Chavez Day 2021-03-31T08:00:00.000Z
Memorial Day 2021-05-31T08:00:00.000Z
Independence Day 2021-07-04T08:00:00.000Z
Labor Day 2021-09-06T08:00:00.000Z
Veterans Day 2021-11-11T08:00:00.000Z
Thanksgiving Day 2021-11-25T08:00:00.000Z
Day after Thanksgiving 2021-11-26T08:00:00.000Z
Christmas Day 2021-12-25T08:00:00.000Z

Related

using week number to get range of dates with sunday as first day of week in python

input: week_number = 34 (or 2022-34)
expected output:
["2022-08-21","2022-08-22", "2022-08-23","2022-08-24","2022-08-25","2022-08-26","2022-08-27"]
First date should be of Sunday
the last date should be Saturday
work with both leap and non leap year
Try:
import datetime
week_number = 34
out = []
date = datetime.datetime.strptime(f"2022-{week_number}-0", "%Y-%U-%w")
for day in range(7):
out.append((date + datetime.timedelta(days=day)).strftime("%Y-%m-%d"))
print(out)
Prints:
[
"2022-08-21",
"2022-08-22",
"2022-08-23",
"2022-08-24",
"2022-08-25",
"2022-08-26",
"2022-08-27",
]
From the reference:
%U - Week number of the year (Sunday as the first day of the week) as
a zero-padded decimal number. All days in a new year preceding the
first Sunday are considered to be in week 0.

How to calculate date of birth, given age expressed in years, months, days, as reported on a given date?

I have a 2 months old dataset, from 15 October 2020, containing the ages of different persons. The age of each person is given in years, months, days.
Example
Input: Reference date = 15 October 2020
One entry in the input data set could be:
Input: Age = 21 years, 0 months, 10 days
Corresponding output: Date of Birth = 25 September 1999
This takes into account that their age was reported on 15 October 2020.
I have to convert this data set to get the Date of Birth of each person. How can I accomplish that?
You can use the dateutil.relativedelta function, which you can use to subtract years, months and days from another date.
I'll assume that you know the exact date on which the data was collected, ... let's say 15 October 2020:
from datetime import date
from dateutil.relativedelta import relativedelta
# Let's say the data was taken on 15 October 2020:
refdate = date(2020, 10, 15)
# The data itself: triplets of years, months, days as collected on 15 October 2020:
data = [
[20, 2, 1],
[53, 5, 10],
]
# Extend the data with the birthdate:
for person in data:
person.append(refdate - relativedelta(years=person[0],
months=person[1],
days=person[2]))
# Print the data:
for person in data:
print("{} years, {} months, {} days: born on {}".format(*person))

Reference table and match date public holiday

I have a table that looks like this (named range PubHols):
Holiday 2018 2019 2020 2021
New Year's Day 01/01/2018 01/01/2019 01/01/2020 01/01/2021
Australia Day 26/01/2018 28/01/2019 27/01/2020 26/01/2021
Good Friday 30/03/2018 19/04/2019 10/04/2020 02/04/2021
Holy Saturday 31/03/2018 20/04/2019 11/04/2020 03/04/2021
Easter Sunday 01/04/2018 21/04/2019 12/04/2020 04/04/2021
Easter Monday 02/04/2018 22/04/2019 13/04/2020 05/04/2021
ANZAC Day 25/04/2018 25/04/2019 25/04/2020 25/04/2021
Queen's Birthday 11/06/2018 10/06/2019 08/06/2020 14/06/2021
Labour Day 01/10/2018 07/10/2019 05/10/2020 04/10/2021
Christmas Day 25/12/2018 25/12/2019 25/12/2020 25/12/2021
Boxing Day 26/12/2018 26/12/2019 26/12/2020 26/12/2021
Trying to incorporate into a function - that is to check if the date is a public holiday first, and then run the ifs.
Current formula is:
=IF($A2="","",IFS(WEEKDAY($A2)=1,"Sun",WEEKDAY($A2)=2,"Weekday",WEEKDAY($A2)=3,"Weekday",WEEKDAY($A2)=4,"Weekday",WEEKDAY($A2)=5,"Weekday",WEEKDAY($A2)=6,"Weekday",WEEKDAY($A2)=7,"Saturday"))
You could put the test for a public holiday into your existing formula like this:
=IFS($A$2="","",COUNTIF(PubHols,A2),"Public Holiday",WEEKDAY($A2)=1,"Sun",WEEKDAY($A2)=2,"Weekday",WEEKDAY($A2)=3,"Weekday",WEEKDAY($A2)=4,"Weekday",WEEKDAY($A2)=5,"Weekday",WEEKDAY($A2)=6,"Weekday",WEEKDAY($A2)=7,"Saturday")
But there are much shorter ways of testing if a date is a working day, e.g. the one described here
=WORKDAY(A2-1,1,PubHols)=A2
So if you wanted to tell if the day was a working day, public holiday, Saturday or Sunday you could use:
=IFS(A2="","",WORKDAY(A2-1,1,PubHols)=A2,"Working Day",WEEKDAY(A2)=1,"Sun",WEEKDAY(A2)=7,"Sat",TRUE,"Public holiday")
It's interesting that the two formulas give different results. I think the reason is that a public holiday should never fall on a weekend, so probably Monday 28th December will be a public holiday this year rather than Saturday 26th.

Get day name from starting date

I developing a course app. In my app, if a student register for a new course, the teacher must input the starting course date for the student.
And in this app, the student can pick up the day that they want to learn to the teacher.
e.g: The student wants to learn 3 days for each week, Monday, Tuesday and Friday.
And for the day that the student taking, they must pay to the teacher on that day.
So, I want my app can automatically display on what day a student must pay the tuition to the teacher.
The thing that I need here is: if the teacher inputted the starting course date on 20-10-2019 (%d-m-Y%), and the days that the student taking are Monday, Tuesday and Friday, I want to print: print('please, pay it') every week on the selected day.
So, I want something like this:
import datetime
starting_course_date = datetime.datetime.strptime("20-10-2019", "%d-%m-%Y")
student_taking_days = [{'day': 'Monday'}, {'day': 'Tuesday'}, {'day': 'Friday'}]
today = datetime.datetime.utcnow()
if today > starting_course_date and today is one of day on the student_taking_days:
print('please, pay it')
Please, any answer, source or refer tutorial will be very appreciated :)
You can get weekday of your today. More info here
import datetime
weekday = datetime.datetime.today().weekday()
if (weekday in [0, 1, 4]): // 0 is monday, 1 is tuesday and 4 is friday
print('please, pay it')
You event can get day name like this using strftime:
weekday_name = weekday.strftime("%A")
if (weekday_name in ['Monday', 'Tuesday', 'Friday']):
print('please, pay it')
weekday = today.weekday()
This gives the result as an integer starting from Monday = 0.
You could directly use this variable in your 'if' statement.
if weekday == 0 or weekday == 1 or weekday == 4:
print('please, pay it')

how to calculate the number of the week in a year?

I would like to calculte the number of the week in a year. I see this post
In this post the acepted answer use this code:
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
However I see a problem. The number of the week is repeated if the last day of a month is in Sunday.
For example, the last day of March of 2013 year is in sunday. This week is the number 13th, is correct. But in April, how C# use always 6 weeks in a month to calculate the number of week, the first week of april has not any day of april, because all the days belong to march because the last day of the week is 30th March. So C# says that the first week of april is th 15th week, but this is incorrect, it has to be 14th.
So I would like to know if there are any way to calculate the number of a week in a right way.
EDIT:
I mean this:
In march, the last week is this:
25 26 27 28 29 30 31
This is the 13th, is correct.
In april, the first week is:
1 2 3 4 5 6 7
And this week is calculated as 15th.
So if I see the march calendar the last week is calculated as 13th and if I see the april calendar the last week of march is caluclated as 14th. This is incorrect.
SOLUTION:
DateTime dtCalendar = Calendar.DisplayDate;
int gridRow = (int)GetValue(Grid.RowProperty);
// Return the week of our adjusted day
int wueekNumber= System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dtCalendar, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);
if (dtCalendar.DayOfWeek == DayOfWeek.Monday)
{
gridRow = gridRow - 1;
}
Text = (weekNumbe r+ gridRow - 1).ToString();
Thanks.
The problem is that you are using the wrong CalendarWeekRule. To get the result you want you should use FirstDay. I have seen various codes in internet saying that you should use FirstFourDayWeek but, after some testing, I realised that the "right one" is FirstDay. I have tested it with your example and it delivers the right result: 14th week.
int targetYear = 2013;
DateTime targetDate = new DateTime(targetYear, 4, 1);
int week = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(targetDate, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);

Resources