Home > Back-end >  consecutive days of login count python
consecutive days of login count python

Time:06-11

I am getting my time in day and month format like this:

final =[{'day': 29, 'month': 5},{'day': 30, 'month': 5},{'day': 1, 'month': 6},{'day': 2, 'month': 6},{'day': 3, 'month': 6},{'day': 4, 'month': 6},{'day': 5, 'month': 6},{'day': 6, 'month': 6}, {'day': 7, 'month': 6}, {'day': 8, 'month': 6}, {'day': 9, 'month': 6}]

I want to check count of consecutive days in array from today to keep count of last online days . and if like my previous day exist it will add 1 in total count. for example {'day': 5, 'month': 6},{'day': 8, 'month': 6}, {'day': 9, 'month': 6} in these three record 6 is missing so my count will be 2 . there is now issue that like if it goes to previous month and there month end is like 30 and month 5 , how I will add this to my count ?

for now : I am doing like this

#getting today day and month and year
today_time = int(time.time())
today_time_day = datetime.datetime.fromtimestamp(today_time)

#to check if previous month day end start
month = monthrange(today_time_day.year, today_time_day.month)
print(month)
i =0 
streak = 0
for x in reversed(final):
    if today_time_day.day - i == x['day']:
        streak  = 1
    else:
        streak = 1
        break
    i  = 1
print(streak)

I am trying to calculate but answer is wrong and not sure how I can use previous month streak .

CodePudding user response:

So the answer is we need to keep track of last month count and reset loop count

today_time = int(time.time())
today_time_day = datetime.datetime.fromtimestamp(today_time)
    
final =[{'day': 29, 'month': 5},{'day': 28, 'month': 5},{'day': 1, 'month': 6},{'day': 2, 'month': 6},{'day': 3, 'month': 6},{'day': 4, 'month': 6},{'day': 5, 'month': 6},{'day': 6, 'month': 6}, {'day': 7, 'month': 6}, {'day': 8, 'month': 6}, {'day': 9, 'month': 6}]


month = monthrange(today_time_day.year, today_time_day.month)
i =0 
current_day = today_time_day.day
streak = 0
for x in reversed(final):
    if  current_day - i == 0 and today_time_day.month -1 == x["month"] : 
        current_day = month[1]
        i = 0
    if current_day - i == x['day']:
        streak  = 1
    else:
        break
    i  = 1
print(streak)
  • Related