How can i get the Current Quarter year and then First Date and last Date of Current Quarter Year in Python?
i want by importing datetime
import datetime
People look into Stack overflow need straight forward answer and which should be very simple. Which ever link you provided it having lot of Comments. SO, users has to go through all the comments to find correct answer. I am writing simple and straight forward answer.
I believe that none of the current answers are still valid in Python 3, so since this is the top hit in google for first and last day of quarter, I will provide a solution that works in Python 3 (mostly Ahmet's with // instead of /):
from datetime import date as date_class
from datetime import timedelta, datetime
def get_quarter(p_date: date_class) -> int:
return (p_date.month - 1) // 3 + 1
def get_first_day_of_the_quarter(p_date: date_class):
return datetime(p_date.year, 3 * ((p_date.month - 1) // 3) + 1, 1)
def get_last_day_of_the_quarter(p_date: date_class):
quarter = get_quarter(p_date)
return datetime(p_date.year + 3 * quarter // 12, 3 * quarter % 12 + 1, 1) + timedelta(days=-1)
assert get_quarter(datetime(year=2021, month=10, day=5).date()) == 4
assert get_quarter(datetime(year=2020, month=9, day=25).date()) == 3
assert get_quarter(datetime(year=2020, month=12, day=11).date()) == 4
assert get_quarter(datetime(year=2020, month=1, day=2).date()) == 1
assert get_first_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 7, 1)
assert get_first_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 10, 1)
assert get_first_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 1, 1)
assert get_last_day_of_the_quarter(datetime(2020, 10, 5).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 9, 25).date()) == datetime(2020, 9, 30)
assert get_last_day_of_the_quarter(datetime(2020, 12, 11).date()) == datetime(2020, 12, 31)
assert get_last_day_of_the_quarter(datetime(2020, 1, 2).date()) == datetime(2020, 3, 31)
assert get_last_day_of_the_quarter(datetime(2020, 5, 6).date()) == datetime(2020, 6, 30)
Having the first day is the same with #Karishh's solution. But, for the last date, Python2.7 causes a problem for fourth quarter. Because 12+1=13 and datetime does not accept 13 as a month. So you need to do some tricks to handle it.
import datetime
def get_quarter(date):
return (date.month - 1) / 3 + 1
def get_first_day_of_the_quarter(date):
quarter = get_quarter(date)
return datetime.datetime(date.year, 3 * quarter - 2, 1)
def get_last_day_of_the_quarter(date):
quarter = get_quarter(date)
month = 3 * quarter
remaining = month / 12
return datetime.datetime(date.year + remaining, month % 12 + 1, 1) + datetime.timedelta(days=-1)
Any how i found some simple solution in c# and converted it into python,
from datetime import datetime,timedelta
current_date=datetime.now()
currQuarter = (current_date.month - 1) / 3 + 1
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = datetime(current_date.year, 3 * currQuarter + 1, 1) + timedelta(days=-1)
Here's a one/two liner to get the start/end date of the current quarter.
from datetime import datetime
import math
from dateutil.relativedelta import relativedelta # requires python-dateutil
start_of_quarter = datetime(year=datetime.now().year, month=((math.floor(((datetime.now().month - 1) / 3) + 1) - 1) * 3) + 1, day=1)
end_of_quarter = start_of_quarter + relativedelta(months=3, seconds=-1)
pendulum has a much more intuitive implementation.
import pendulum
dt = pendulum.datetime(2021, 3, 23)
print(dt.first_of('quarter'))
print(dt.last_of('quarter'))
2021-01-01T00:00:00+00:00
2021-03-31T00:00:00+00:00
Building off of the answer from Krishh, but addressing several issues found:
calculating last day in Quarter 4
Wasae Shoaib's comment about raising a ValueError
TypeError with a float being passed instead of an integer
Using relativedeta instead and shifting the correctly calculated start date by three months, we end up with a much more reliable way to get at the quarter end date.
from datetime import datetime
from dateutil.relativedelta import relativedelta
current_date = datetime.now()
currQuarter = int((current_date.month - 1) / 3 + 1)
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = dtFirstDay + relativedelta(months=3, days=-1)
I did of a lot of tests to find the solution that fit my need and I will be happy if it helps someone else :
datval = fields.date.today()
if datval.month < 4 :
self.start_date = fields.date.today().replace(month=10, day=1)
self.end_date = fields.date.today().replace(month=12, day=31)
elif datval.month < 7 :
self.start_date = fields.date.today().replace(month=1, day=1)
self.end_date = fields.date.today().replace(month=3, day=31)
elif datval.month < 10 :
self.start_date = fields.date.today().replace(month=4, day=1)
self.end_date = fields.date.today().replace(month=6, day=30)
else :
self.start_date = fields.date.today().replace(month=7, day=1)
self.end_date = fields.date.today().replace(month=9, day=30)
Get start and end points for: week, month, quarter and year
https://gist.github.com/dejurin/236b398dc4b8064685702a27a3df612b
from datetime import date
from dateutil.relativedelta import relativedelta
def start_end_day(sunmon: bool = True):
today = date.today()
curr_quarter = int((today.month - 1) / 3 + 1)
dayofweek = [today.weekday(),today.isoweekday()][sunmon]
week_start = today - relativedelta(days=dayofweek)
week_end = week_start + relativedelta(days=6)
month_start = date(today.year,today.month, 1)
month_end = month_start + relativedelta(months=1, days=-1)
quarter_start = date(today.year, 3 * curr_quarter - 2, 1)
quarter_end = quarter_start + relativedelta(months=3, days=-1)
year_start = date(today.year, 1, 1)
year_end = year_start + relativedelta(years=1, days=-1)
return ((week_start,week_end),(month_start,month_end),(quarter_start,quarter_end),(year_start,year_end))
"""
Current date: 18/02/2022
"""
"""
((datetime.date(2022, 2, 13), datetime.date(2022, 2, 19)),
(datetime.date(2022, 2, 1), datetime.date(2022, 2, 28)),
(datetime.datetime(2022, 1, 1, 0, 0), datetime.datetime(2022, 3, 31, 0, 0))
(datetime.date(2022, 1, 1), datetime.date(2022, 12, 31)))
"""
Related
Solving an agent scheduling problem using PuLP.
8 hours of shift, 4 agents.
I have to generate an output where the 8 hrs of shift is divided into 15-minute intervals. Hence, 32 total periods. (the 15 minute periods of an 8 hour shift is a fixed input, which is not allowed to be tweaked.)
At any given period, there need to be a minimum of 3 agents working (i.e.not on break)
Now, there needs to be a 1 hour meal break, and a 30 min short break.
So, for 1 hour meal break, I will have to combine 4 periods of 15 mins, and for the 30 min short break, I'll have to combine 2 periods of 15 mins.
I tried getting 26 counts of 1... and, 6 counts of 0.
The idea was to then combine 4 zeros together (meal break), and the remaining 2 zeros together (short break).
The current LpStatus is 'infeasible'... if i remove the constraint where i am trying to club the zeros, then the solution is optimal, or else it shows infeasible.
Have also pasted my final dataframe output screenshots.
import pandas as pd
import numpy as np
import scipy as sp
import seaborn as sns
import matplotlib.pyplot as plt
from pandas.plotting import table
import os, sys, json
from pulp import *
%matplotlib inline
# agent works either 1, 2, 3, 4, 5, 6, 7, 8 hours per week.
working_periods = [26]
# maximum periods that agent will work (7 hrs in each shift)
max_periods = 26
# planning_length
planning_length = 1 # TODO: Total number of shifts i.e. 21 in our case
# Number of periods per shift:
daily_periods = [0, 1, 2, 3, 4, 5, 6, 7, 8,9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
# Label the days from Monday to Sunday.
s = ['Period']
# Create the required_agents dataframe
col_2 = range(0, 1*planning_length)
required_agents_per_period = pd.DataFrame(data = None, columns=s, index = daily_periods)
for j in col_2:
# Small number is better for visualization.
required_agents_per_period.iloc[0][j] = 3
required_agents_per_period.iloc[1][j] = 3
required_agents_per_period.iloc[2][j] = 3
required_agents_per_period.iloc[3][j] = 3
required_agents_per_period.iloc[4][j] = 3
required_agents_per_period.iloc[5][j] = 3
required_agents_per_period.iloc[6][j] = 3
required_agents_per_period.iloc[7][j] = 3
required_agents_per_period.iloc[8][j] = 3
required_agents_per_period.iloc[9][j] = 3
required_agents_per_period.iloc[10][j] = 3
required_agents_per_period.iloc[11][j] = 3
required_agents_per_period.iloc[12][j] = 3
required_agents_per_period.iloc[13][j] = 3
required_agents_per_period.iloc[14][j] = 3
required_agents_per_period.iloc[15][j] = 3
required_agents_per_period.iloc[16][j] = 3
required_agents_per_period.iloc[17][j] = 3
required_agents_per_period.iloc[18][j] = 3
required_agents_per_period.iloc[19][j] = 3
required_agents_per_period.iloc[20][j] = 3
required_agents_per_period.iloc[21][j] = 3
required_agents_per_period.iloc[22][j] = 3
required_agents_per_period.iloc[23][j] = 3
required_agents_per_period.iloc[24][j] = 3
required_agents_per_period.iloc[25][j] = 3
required_agents_per_period.iloc[26][j] = 3
required_agents_per_period.iloc[27][j] = 3
required_agents_per_period.iloc[28][j] = 3
required_agents_per_period.iloc[29][j] = 3
required_agents_per_period.iloc[30][j] = 3
required_agents_per_period.iloc[31][j] = 3
# List of number of agents required in specific periods
r_p = required_agents_per_period.values.swapaxes(0,1).ravel()
print("The number of agents required for each period is: ")
print (r_p)
print("Total no. of periods is: ", len(r_p))
print ("\nIn matrix form:")
print (required_agents_per_period)
# Total number of the agents
total = 4
print ("\nTotal number of agents are: {}".format(total))
# Create agents_id tag
agent_id_working_in_shift = ['agent7', 'agent10', 'agent13', 'agent18'] # TODO: Important: Here agent_id will be array of agents that will be extracted from dataframe.
print ("\nThe agents are: ")
print (agent_id_working_in_shift)
# Total periods
periods = range(1*32)
agents_per_shift = range(total)
## Create shift names based on index:
period_name = []
for p in periods:
period_name.append(s[0] + '_' + 'P' + str(p))
print("The periods are: ")
print(periods)
print("\nThe names of corresponding periods are: ")
print(period_name)
print("\nThe agents are: ")
print(agents_per_shift)
def LpProb():
# The prob variable is created to contain the problem data
prob = LpProblem("Agents Meal Scheduling Per Shift",LpMinimize)
# Creating the variables.
var = {
(n, p): pulp.LpVariable(
"schdule_{0}_{1}".format(n, p), cat = "Binary")
for n in agents_per_shift for p in periods
}
# add constraints:
for n in agents_per_shift:
for p in periods:
prob.addConstraint(var[(n,p)] <= 1)
# add constraints:
# Exactly 32 working periods per shift
for n in agents_per_shift:
prob.addConstraint(
sum(var[(n,p)] for p in periods) == 26
)
for n in agents_per_shift:
for p in periods:
if(p == periods[-1] or p == periods[-2] or p == periods[-3]):
continue
prob.addConstraint(var[(n,p)] + var[(n,p+1)] + var[(n,p+2)] + var[(n,p+3)] == 0)
# add constraints
# for each shift, the numbers of working agents should be greater than or equal to
# the required numbers of agents
for p in periods:
try:
prob.addConstraint(
sum(var[(n,p)] for n in agents_per_shift) >= 3
)
except:
print("len(periods) should be equal to len(agents_per_shift)")
sys.exit(-1)
prob.objective = sum(var[(n,p)] for n in agents_per_shift for p in periods)
return var, prob
# Run the solver
var, prob = LpProb()
prob.solve()
print(LpStatus[prob.status])
def agent_scheduling(var = var):
schedule = pd.DataFrame(data=None, index = agent_id_working_in_shift, columns = period_name)
for k, v in var.items():
n, p = k[0], k[1]
schedule.iloc[n][p] = int(value(v)) # pulp.value()
return schedule
schedule = agent_scheduling()
schedule.T
I was expecting an output of only zeros and one.
Want to combine four 0's as meal break, that need to be consecutive, and then a two 0's consecutive for short break (remaining 26 cells should be 1's)
Also, only 1 agent can be on a break (0), the other 3 agents needs to be working in that period (1)
OUTPUTS:-
enter image description here
enter image description here
enter image description here
I am coding an optimization problem. The model is giving infeasible solution. I want to check which constraint is giving infeasible solution. So far, I have checked online, but have not been able to come up with the solution to the problem. Can anyone help me? For example:in the code below, because of constraint 3 model is infeasible. How do I determine it from the solution? Thanks
from gurobipy import *
# Create a new model
m = Model("mip1")
# Create variables
x1 = m.addVar(vtype=GRB.INTEGER, name="x1")
x2 = m.addVar(vtype=GRB.INTEGER, name="x2")
# Integrate new variables
m.update()
# Set objective
m.setObjective(7*x1 + 2*x2, GRB.MAXIMIZE)
m.addConstr(-x1 + 2 * x2 <= 4, "constraint-0")
m.addConstr(5*x1 + x2 <= 20, "constraint-1")
m.addConstr(-2*x1 -2*x2 <= -7, "constraint-2")
m.addConstr(x1 <= -2, "constraint-3")
m.addConstr(x2 <= 4, "constraint-4")
m.optimize()
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
print('Obj: %g' % m.objVal)
an exemple :
from gurobipy import *
# Create a new model
m = Model("mip1")
# Create variables
x1= m.addVar(lb=0,ub=62,vtype=GRB.INTEGER,name="x1")
x2 = m.addVar(lb=0,ub=50, vtype=GRB.INTEGER,name="x2")
m.update()
m.addConstr(-x1 + 2*x2 <= 4, "constraint-0")
m.addConstr(5*x1 + x2 <= 20, "constraint-1")
m.addConstr(-2*x1 -2*x2 <= -25, "constraint-2")
m.addConstr(x1 <= 2, "constraint-3")
#m.addConstr(x2 <= 50, "constraint-4")
m.update()
# Set objective
m.setObjective(7*x1 + 2*x2, GRB.MAXIMIZE)
m.update()
m.optimize()
status = m.status
if status == GRB.Status.OPTIMAL:
for v in m.getVars():
print('%s %g' % (v.varName, v.x))
print('Obj: %g' % m.objVal)
elif status == GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % status)
# do IIS
m.computeIIS()
for c in m.getConstrs():
if c.IISConstr:
print('%s' % c.constrName)
I have a function that will calculate 6 days, it works, and it's wonderful and all, but I need a way to skip Saturday and Sunday. How can I fix this function in order to have it skip Saturday and Sunday?
def calc_bus_day(start_day):
if start_day.isoweekday() in range(1, 5):
shift = 6
returnDate = start_day + datetime.timedelta(days=shift)
if returnDate.isoweekday() == 0:
return "{:%m-%d-Y}".format(returnDate + datetime.timedelta(days=1))
elif returnDate.isoweekday() == 5:
return "{:%m-%d-%Y}".format(returnDate + datetime.timedelta(days=2))
else:
return "{:%m-%d-%Y}".format(returnDate)
As shifting for 6 days always includes shifting over a weekend, you can shift for 8 days (6 days + Saturday and Sunday):
def calc_bus_day(start_day):
if start_day.isoweekday() in range(1, 5):
shift = 8
< your code >
You can use this code that I use. The attempt it is add not just 6 days, but any number of days.
from datetime import datetime, timedelta, date
def getNextBusinessDays(date, num):
for i in range(0, num):
date = getNextBusinessDay(date)
return date
def getNextBusinessDay(fromDate):
nextBuinessDate = datetime.strptime(fromDate, "%Y-%m-%d")
nextBuinessDate = nextBuinessDate + timedelta(days=1)
if date.weekday(nextBuinessDate) not in range(0, 5):
nextBuinessDate = nextBuinessDate + timedelta(days=1)
if date.weekday(nextBuinessDate) not in range(0, 5):
nextBuinessDate = nextBuinessDate + timedelta(days=1)
return nextBuinessDate.strftime('%Y-%m-%d')
For example getNextBusinessDays('2016-10-20', 6) will produce "2016-10-28"
I have a simple PyQt GUI which gives values which I would like to turn into a datetime format.
At the moment it is printing
201011
Whereas I would like it to print
2010,1,1
Here is the PyQt code,
*timer.py
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(510, 129)
self.gridLayout = QtGui.QGridLayout(Dialog)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.frame = QtGui.QFrame(Dialog)
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName(_fromUtf8("frame"))
self.gridLayout_2 = QtGui.QGridLayout(self.frame)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.yearlabel = QtGui.QLabel(self.frame)
self.yearlabel.setObjectName(_fromUtf8("yearlabel"))
self.gridLayout_2.addWidget(self.yearlabel, 0, 0, 1, 1)
self.monthfromcomboBox = QtGui.QComboBox(self.frame)
self.monthfromcomboBox.setObjectName(_fromUtf8("monthfromcomboBox"))
self.gridLayout_2.addWidget(self.monthfromcomboBox, 1, 2, 1, 2)
self.label_2 = QtGui.QLabel(self.frame)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout_2.addWidget(self.label_2, 0, 4, 1, 1)
self.SearchButton = QtGui.QPushButton(self.frame)
self.SearchButton.setObjectName(_fromUtf8("SearchButton"))
self.gridLayout_2.addWidget(self.SearchButton, 2, 4, 1, 2)
self.yearfromcomboBox = QtGui.QComboBox(self.frame)
self.yearfromcomboBox.setObjectName(_fromUtf8("yearfromcomboBox"))
self.gridLayout_2.addWidget(self.yearfromcomboBox, 1, 0, 1, 2)
self.dayfromcomboBox = QtGui.QComboBox(self.frame)
self.dayfromcomboBox.setObjectName(_fromUtf8("dayfromcomboBox"))
self.gridLayout_2.addWidget(self.dayfromcomboBox, 1, 4, 1, 2)
self.label = QtGui.QLabel(self.frame)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_2.addWidget(self.label, 0, 2, 1, 1)
self.gridLayout.addWidget(self.frame, 0, 0, 1, 1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
Dialog.setTabOrder(self.yearfromcomboBox, self.monthfromcomboBox)
Dialog.setTabOrder(self.monthfromcomboBox, self.dayfromcomboBox)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.yearlabel.setText(_translate("Dialog", "Year", None))
self.label_2.setText(_translate("Dialog", "Day", None))
self.SearchButton.setText(_translate("Dialog", "Go", None))
self.label.setText(_translate("Dialog", "Month", None))
The corresponding python code is,
import sys
import datetime
from PyQt4 import QtCore, QtGui
from timer import *
from PyQt4.QtGui import (QApplication, QTabWidget, QWidget,
QStyle, QStyleFactory)
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
style = QStyleFactory.create('Cleanlooks')
app.setStyle(style)
QtCore.QObject.connect(self.ui.SearchButton, QtCore.SIGNAL('clicked()'), self.search)
months = range(1,13)
for iitem in months:
Months = str(iitem)
self.ui.monthfromcomboBox.addItem(Months)
days = range(1,32)
for iitem in days:
Days = str(iitem)
self.ui.dayfromcomboBox.addItem(Days)
years = range(2010, 2017)
for iitem in years:
Years = str(iitem)
self.ui.yearfromcomboBox.addItem(Years)
def search(self):
nowyear = int(self.ui.yearfromcomboBox.currentText())
nowmonth = int(self.ui.monthfromcomboBox.currentText())
nowday = int(self.ui.dayfromcomboBox.currentText())
nowdate = int('%d%d%d' %(nowyear,nowmonth,nowday))
print nowdate
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
viewer = Window()
viewer.show()
sys.exit(app.exec_())
I'd recommend using datetime.datetime.strptime:
from datetime import datetime
date_int = 201011
date = datetime.strptime(str(date_int), '%Y%m%d')
print '{},{},{}'.format(date.year, date.month, date.day)
2010,1,1
Here is my solution:
dateNum = 201011
dateNum = str(dateNum)
year = dateNum[:4]
monthDay = dateNum[4:]
if len(monthDay) == 2:
day = monthDay[1:]
month = monthDay[:1]
print(year + "," + month + "," + day)
This will output:
2010,1,1
The only problem with this code is that you cannot determine dates such as:
2014111 which should be November 1st but could also be January 11th
Is there any way you can change the format to include leading zeros? (e.g. 20141101 for Nov 1st 2014)
Maybe someone else has a way to determine this. However I think logically the format makes it impossible to determine one or the other.
This code is redefined to handle the leading zeros:
dateNum = 20100101
dateNum = str(dateNum)
year = dateNum[:4]
monthDay = dateNum[4:]
day = monthDay[2:]
month = monthDay[:2]
print(year + "," + month + "," + day)
2010,01,01
There's no reason to convert your date parts into a string and then to an single integer if you don't actually need that integer for something. Get rid of this line:
nowdate = int('%d%d%d' %(nowyear,nowmonth,nowday))
And instead use the individiual date components however you want. It could be as simple as print nowyear, nowmonth, nowday (which will print them separated by spaces), or you could do something more complicated like using them to create something from the datetime module which you can use later (or print in a wide variety of formats).
To get the output you specifically request ('2010,1,1'), you can keep it pretty close to your existing code. Just use print '%d,%d,%d' % (nowyear, nowmonth, nowday), or if you want to use the newer str.format syntax, print '{:d},{:d},{:d}'.format(nowyear, nowmonth, nowday). If you wanted the single-digit month or days to use two characters (so they're always the same width), you could use %02d or {:02d} in the format strings, to request zero-padding to a width of two.
I'm trying to plot a graph that shows the average call duration every day each minute for 7 days in the same plot, now I'm defining the function that will give me the data asked according to conditions which will be plotted but I'm always getting a list of empty lists.can any one help me tof ind the bug? (acc is just an example of data from the global database)
This is the function:
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
try:
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
except:
pass
donnees.append(data)
print donnees
This is due to your try / except condition, if you remove it by settings temps = None after your loop it solves you issue :
import time
import calendar
from datetime import datetime
from itertools import repeat
acc=[{u'switch_id': 3, u'hangup_cause_id': 7, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 1), u'duration': 32}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 8), u'duration': 20}, {u'switch_id': 3, u'hangup_cause_id': 10, u'start_uepoch': datetime(2015, 5, 8, 13, 32, 10), u'duration': 17}]
t = datetime.now()
y = t.year
m = t.month
d = t.day
donnees=[]
for k in range(7):
m = t.month
data=[]
liste=[]
liste_time=[]
for i in acc:
if (i["start_uepoch"].year == y and i["start_uepoch"].month == m and i["start_uepoch"].day == d-k):
liste.append([i["start_uepoch"],i["duration"]])
for q in range(24):
for mnt in range(60):
temps = None
liste2=[]
ACD=0
somme_duration=0
n=0
for p in liste:
if (p[0].hour==q and p[0].minute == mnt):
liste2.append(p[1])
temps=p[0]
if temps:
if len(liste2)!=0:
for j in liste2:
somme_duration+=j
n+=1
ACD=round((float(somme_duration)/n)*100)/100
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(ACD)
else:
liste_time.append(calendar.timegm(temps.timetuple()))
data.append(0)
donnees.append(data)
print donnees