I am teaching myself Python. I have gone through some tutorials and thought I'd write a little program for counting the candles for each of the respective 8 nights of Hanukkah.
days = 0
candles = 1
while days <= 8 :
days = days + 1
candles = candles + 1
print ("Day", days,":", candles, "Candles")
But the results for this (Python 3.4) are:
Day 1 : 2 Candles
Day 2 : 3 Candles
Day 3 : 4 Candles
Day 4 : 5 Candles
Day 5 : 6 Candles
Day 6 : 7 Candles
Day 7 : 8 Candles
Day 8 : 9 Candles
Day 9 : 10 Candles
Why didn't it stop at day 8?
Because you days <= 8 when the loop starts, then you add one to it in the loop. while loops don't stop the second the value changes they finish executing the block and then return to the conditional and check if they should keep going.
You are incrementing the value of the variable days after the test. When days is 8, you increment it to 9 and then you print it.
I would do something like this:
days = 1
candles = 2
while days <= 8 :
print ("Day", days,":", candles, "Candles")
days = days + 1
candles = candles + 1
If you increase your variables at the end you will get what you want.
days = 1
candles = 2
while days <= 8 :
print ("Day", days,":", candles, "Candles")
days = days + 1
candles = candles + 1
Related
I want to create a new variable in which the weeks are assigned but i don't want the week to overlap between 2 months. So suppose in Jan'23 week 5 has 30,31 and the rest from Feb 1,2,3 and so on. Jan 30,31 should be assigned week5 and the dates from Feb as week6
import datetime
import time
def getDateRangeFromWeek(p_year,p_week):
firstdayofweek = datetime.datetime.strptime('{}-W{}-1'.format(p_year,int(p_week)-1), "%Y-W%W-%w").date()
lastdayofweek = firstdayofweek + datetime.timedelta(days=7)
return firstdayofweek, lastdayofweek
this function gives me the first day and last day of a week and bases this i define the week
for i in frange('1-53'):
firstdate, lastdate = getDateRangeFromWeek('2023',str(i))
dataset[(dataset['starttime'] >= firstdate) & (dataset['starttime'] <= lastdate), 'week_DP_2023'] = i
You can create a list of dates to use with pd.cut:
# create a minimal reproducible example
df = pd.DataFrame({'starttime': pd.date_range('2023-01-20', '2023-02-10')})
# generate all days of a year
dti = pd.date_range('2023-1-1', '2023-12-1')
# keep only monday and first day of month as bins
dti = dti[(dti.weekday == 0) | (dti.day == 1)]
# set week number according requirements
df['week'] = pd.cut(df['starttime'], bins=dti, labels=range(len(dti)-1), right=False)
Output:
>>> df
starttime week
0 2023-01-20 3
1 2023-01-21 3
2 2023-01-22 3
3 2023-01-23 4
4 2023-01-24 4
5 2023-01-25 4
6 2023-01-26 4
7 2023-01-27 4
8 2023-01-28 4
9 2023-01-29 4
10 2023-01-30 5 # Monday
11 2023-01-31 5 # Thuesday
12 2023-02-01 6 # Wednesday, another month week+1
13 2023-02-02 6 # Thursday
14 2023-02-03 6 # Friday
15 2023-02-04 6 # Saturday
16 2023-02-05 6 # Sunday
17 2023-02-06 7 # A new week begins
18 2023-02-07 7
19 2023-02-08 7
20 2023-02-09 7
21 2023-02-10 7
Hi so I have a dataframe on IT ticket incoming time that looks like this
Feedback time time hour Shift
0 12/2/20 23:58 2020-12-02 23:58:00 23 Shift 3
1 12/2/20 10:20 2020-12-02 10:20:00 10 Shift 1
2 12/2/20 11:40 2020-12-02 11:40:00 11 Shift 1
....
458 11/18/20 16:01 2020-11-18 16:01:00 16 Shift 2
Here the earliest date is 11/18/2020 and latest is 12/2/2020
And "Shift" is defined as
conditions = [(df['hour'] >= 7) & (df['hour'] < 15),
(df['hour'] >= 15) & (df['hour'] < 23),
(df['hour'] < 7) | (df['hour'] >= 23)]
Expected output
11/18-11/25 11/26-12/2
Shift Hour
Shift 1 7 xx
8
9
...
15
Shift 2 16
17
...
22
Shift 3 23
0
1
...
6
Basically column will be groupby week, index will be Shift and then hour during the day.
For xx, I want to count the frequency of "hour" during 7am interval, sum for the whole week, and then get the average value for that whole week (11/18-11/25 in this case), also need it to populate all the empty cells.
I have tried this
s = pd.pivot_table(df,index=['Shift',"Hour"],columns =['Time'] ,values = ['hour'],aggfunc=[len])
but my first row is only showing every day, not aggregated by week
Thank you so much!
I Have a df having 2 columns *Total Idle Time and Month as below:
Total Idle Time Month
0 0:00:00 December
1 0:02:24 December
2 26:00:00 December
3 0:53:05 December
4 28:03:39 December
Here the Total Idle Time column is of string format, but I want to convert it into time format as I want to add the total idle time in the month of December.
I tried converting the column to datetime as below:
data['Total Idle Time '] = pd.to_datetime(data['Total Idle Time '], format='%H:%M:%S')
However, I got an error as follow:
time data '28:03:39' does not match format '%H:%M:%S' (match)
I thought of converting the column to int and adding them up based on the hours and minutes, but I am not successful in doing so. Is there any way to do this thing?
You could try using pd.to_timedelta() instead here:
>>> df['Idle Time'] = pd.to_timedelta(df["Idle Time"])
>>> df
Total Idle_Time Month
0 0 0 days 00:00:00 December
1 1 0 days 00:02:24 December
2 2 1 days 02:00:00 December
3 3 0 days 00:53:05 December
4 4 1 days 04:03:39 December
You can use this to convert to numeric if you want, by scaling the results of .total_seconds():
# in hours
>>> df['Idle Time'] = df['Idle Time'].dt.total_seconds() / 3600
>>> df
Total Idle_Time Month
0 0 0.000000 December
1 1 0.040000 December
2 2 26.000000 December
3 3 0.884722 December
4 4 28.060833 December
I have two times, how can I get the time difference of these 2 aware datetime objects in a human readable format. What I mean by human readable format would be 1 year 3 months 2 weeks 4 days 1 hour 2 minutes and 19 seconds.
However, if the time difference is shorter, it would give a readable format like 2 minutes and 3 seconds (It wouldn't tell us 0 years 0 months 0 weeks 0 days 0 hours 2 minutes and 52 seconds). Or if its just seconds left then it would be 15 seconds
Year is classified as 365.25 days
Month is classified as 30.4375 days
Can someone tell me how to get a week number in Python for actual calendar.
Ex: 2016-01-01 to 2016-01-07 = week 1
2016-01-08 to 2016-01-14 = week 2
I tried 2 ways but none of them are working
Using isocalendar()
But that does not work for year end and year start week. For ex:
datetime.date(2016,01,01).isocalendar()[1]
# should be: 1
# got 53
is the following:
dt = date(2016,01,02)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 00
dt = date(2016,01,03)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 01
Both the ways do not satisfy my requirement. Is there any other library I can use to get the week number in Actual Calendar ?
Are you talking about actual number of 7 day periods rather than which week number you're in? Keep in mind in 2016, Jan 3rd is the first day of the second week.
If you're looking at which 7 day period, you should simply count days since the beginning of the year and floor div by 7
dt = datetime.datetime(year=2016, month=1, day=2)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
The 29th should be the first day of week 5. Let's try it.
dt = datetime.datetime(year=2016, month=1, day=29)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
# 5