I made a cell where I can enter the company name and my query filters the results to only show records from that specific company.
Example 1: Here I type 'TestCompany1':
Example 2: Here I type 'TestCompany2':
What I wish to achieve is that when the cell value is blank, it shows all companies. Now it shows all empty. How can I change the query to also allow this?
if you want to use IF statement then:
=IF(B3<>"", QUERY(Company_overview!A2:L,
"where B = '"&B3&"'
and L >= datetime '"&TEXT(TODAY()-B4, "yyyy-MM-dd hh:mm:ss")&"'
and L <= datetime '"&TEXT(NOW(), "yyyy-MM-dd hh:mm:ss")&"'", 1),
QUERY(Company_overview!A2:L,
"where L >= datetime '"&TEXT(TODAY()-B4, "yyyy-MM-dd hh:mm:ss")&"'
and L <= datetime '"&TEXT(NOW(), "yyyy-MM-dd hh:mm:ss")&"'", 1))
or maybe:
=QUERY(Company_overview!A2:L,
"where "&IF(B3<>"", "B = '"&B3&"' and ", )&"
L >= datetime '"&TEXT(TODAY()-B4, "yyyy-MM-dd hh:mm:ss")&"'
and L <= datetime '"&TEXT(NOW(), "yyyy-MM-dd hh:mm:ss")&"'", 1)
Related
I'm trying to have subtraction of two data fields and the result in days. But I'm having time also at the output. How do I get only days not the time.
Here is my code:
class ItemTable(models.Model):
expdate = models.DateField("EXP Date", null=True, blank=True)
def days_to_exp(self):
if self.expdate:
now = datetime.date.today()
exp = str(self.expdate - now)
if exp > "1":
return exp
elif exp < "1" and exp > "0":
return "Today"
else:
return "Expired"
output:
12 days, 0:00:00,
4 days, 0:00:00... etc
I just want the result as:
12 days,
4 days..... etc
The result of subtracting one datetime.date from another is a timedelta object. You can access the .days attribute of that timedelta object to get what you're after.
> today = datetime.now().date()
> tomorrow = today + timedelta(days=1)
> (tomorrow - today).days
1
> (today - tomorrow).days
-1
Result of subtraction between datetime.date instances is an object with type of datetime.timedelta that represents a duration not datetime.date nor datetime.datatime. you can get how long a timedelta is by accessing it's .days property.
for example:
result = now().today() - (now()+timedelta(days=10))
assert(result.days==10)
Here is the piece I am trying to write the value inside existing excel sheet in particular cell but value is not printing inside that sheet,how to write that value,here I used xlutils.copy
from datetime import datetime, timedelta, date
from xlrd import open_workbook
from xlwt import Workbook
from xlutils.copy import copy
import xlrd
import datetime
book = open_workbook('Data.xlsx')
sheet = book.sheet_by_index(0)
# read header values into the list
keys = [sheet.cell(0, col_index).value for col_index in xrange(sheet.ncols)]
dict_list = []
#read the excel sheet data into list
for row_index in xrange(1, sheet.nrows):
d = {keys[col_index]: sheet.cell(row_index, col_index).value
for col_index in xrange(sheet.ncols)}
dict_list.append(d)
TotalEffort = 0
#convert the integer date to YMD format
for count in range(len(dict_list)):
year, month, day, hour, minute, second = xlrd.xldate_as_tuple(dict_list[count]["Date"],book.datemode)
#print week number
if datetime.date.today().isocalendar()[1] == date(year, month, day).isocalendar()[1]:
TotalEffort = TotalEffort+dict_list[count]["Effort"]
weeknum = str(datetime.date.today().isocalendar()[1])
Total = str(TotalEffort)
print " Effort for week"+weeknum+" is: "+Total+"hours"
rb = open_workbook('output.xlsx')
ws = rb.sheet_by_index(0)
for rowidx in range(ws.nrows):# number of rows in sheets
row = ws.row(rowidx)# count row from 0 and get it frm sheet
for colidx, cell in enumerate(row):#read all rows in sheets
if cell.value == "search word":
print 'row ' ,rowidx
print 'column' ,colidx
cur_row = rowidx+2
cur_col = colidx+36
wb = copy(rb)
#pic first sheet
shw = wb.get_sheet(0)
value = str(Total)
#writing to shw
shw.write(cur_row,cur_col,'value')
I am trying to teach myself how to use xlrd for a (conceptually) simple task:
I want to take a string through raw_input from the user and search an excel sheet for the string.
when found I want the program to print the cell row only
here is my non-working code to start with:
import xlrd
from xlrd import open_workbook
book = open_workbook('simple.xls')
sheet = book.sheet_by_index(0)
city = raw_input("> ")
for rowi in range(sheet.nrows):
row = sheet.row(rowi)
for coli, cell in enumerate(row):
if cell.value == city:
loc = cell.row
??????????????
cell = sheet.cell(loc, 9)
print "The Ordinance Frequency is %r" % cell.value
Try cycling through the columns in the same way that you cycle through rows
for r in range(sheet.nrows):
for c in range(sheet.ncols):
cell = sheet.cell(r, c)
if cell.value == city:
loc = r //index of interesting row
import pandas as pd
import numpy as np
import datetime as dt
# Create Column names
col_names = ['930', '931', '932', '933', '934', '935']
# Create Index datetimes
idx_names = pd.date_range(start = dt.datetime(2011, 1, 1), periods = 10, freq= 'D')
# Create dataframe with previously created column names and index datetimes
df1 = pd.DataFrame(np.random.randn(10, 6), columns=col_names, index=idx_names)
# Change the column names from strings to datetimes.time() object
df1.columns = [dt.datetime.strptime(x, '%H%M').time() for x in df1.columns]
# This step and the next step changes the dataframe into a chronological timeseries
df2 = df1.T.unstack()
df2.index = [dt.datetime.combine(x[0], x[1]) for x in df2.index.tolist()]
# Show the series
df2
Question: What is the most pythonic/pandas-thonic way to create a specific list? This list would say 'Every time the difference between 9:32 and 9:34 is between 0 and .50, what is the difference between 9:34 and the next day's 9:34.
I was doing this with the numbers in a dataframe format (dates along the x-axis and times along the y-axis) and I would say something like (below is pseudo-code, above is not pseudo-code):
# Create a column with wrong answers and right answers
df['Today 934 minus yesterday 934'] = df[934] - df[934].shift(1)
# Boolean mask were condition 1 (diff > 0) and condition 2 (diff < .5) are true
mask = (df[934].shift(1) - df[932].shift(1) > 0) & (df[934].shift(1) - df[932].shift(1) < .5)
# Apply the boolean mask to the dataframe. This is will remove all the answers
# I dont want from the df['Today 934 minus yesterday 934'] column
df2 = df[mask]
# Only the answers I want:
answers = df['Today 934 minus yesterday 934']
My attempt, basically a filled in version of your pseudo-code. Someone else may have a cleaner approach.
mask1 = (df2.index.hour == 9) & (df2.index.minute == 34)
mask2 = (df2.index.hour == 9) & (df2.index.minute == 32)
diff_934 = df2[mask1] - df2[mask1].shift(-1)
diff_934 = diff_934[diff_934.index.minute == 34]
diff_932 = df2[mask1|mask2] - df2[mask1|mask2].shift(-1)
diff_932 = diff_932[diff_932.index.minute == 34]
diff_932 = diff_932[(diff_932 > 0) & (diff_932 < .5)]
answer = diff_934.reindex(diff_932.index)
In [116]: answer
Out[116]:
2011-01-02 09:34:00 -0.874153
2011-01-08 09:34:00 0.186254
dtype: float64
I've got a model similar to this:
class Person(models.Model):
name = models.CharField(max_length=40)
birthday = DateTimeField() # their next birthday
I would like to get a list of the total birthdays for each day for the next 30 days. So for example, the list would look like this:
[[9, 0], [10, 3], [11, 1], [12, 1], [13, 5], ... #30 entries in list
Each list entry in the list is a date number followed by the number of birthdays on that day. So for example on the 9th of May there are 0 birthdays.
UPDATES
My db is sqlite3 - will be moving to postgres in the future.
from django.db.models import Count
import datetime
today = datetime.date.today()
thirty_days = today + datetime.timedelta(days=30)
birthdays = dict(Person.objects.filter(
birthday__range=[today, thirty_days]
).values_list('birthday').annotate(Count('birthday')))
for day in range(30):
date = today + datetime.timedelta(day)
print "[%s, %s]" % (date, birthdays.get(date, 0))
I would get the list of days and birthday count this way:
from datetime import date, timedelta
today = date.today()
thirty_days = today + timedelta(days=30)
# get everyone with a birthday
people = Person.objects.filter(birthday__range=[today, thirty_days])
birthday_counts = []
for date in [today + timedelta(x) for x in range(30)]:
# use filter to get only birthdays on given date's day, use len to get total
birthdays = [date.day, len(filter(lambda x: x.birthday.day == date.day, people))]
birthday_counts.append(birthdays)
Something like this --
from datetime import date, timedelta
class Person(models.Model):
name = models.CharField(max_length=40)
birthday = models.DateField()
#staticmethod
def upcoming_birthdays(days=30):
today = date.today()
where = 'DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) BETWEEN DATE(NOW()) AND DATE_ADD(NOW(), INTERVAL %S DAY)'
birthdays = Person.objects.extra(where=where, params=[days]).values_list('birthday', flat=True)
data = []
for offset in range(0, days):
i = 0
d = today + timedelta(days=offset)
for b in birthdays:
if b.day == d.day and b.month == d.month:
i += 1
data.append((d.day, i))
return data
print Person.upcoming_birthdays()
(Queryset of people with a birthday in the next X days)
Found cool solution for this!
For me it works!
from datetime import datetime, timedelta
import operator
from django.db.models import Q
def birthdays_within(days):
now = datetime.now()
then = now + timedelta(days)
# Build the list of month/day tuples.
monthdays = [(now.month, now.day)]
while now <= then:
monthdays.append((now.month, now.day))
now += timedelta(days=1)
# Tranform each into queryset keyword args.
monthdays = (dict(zip(("birthday__month", "birthday__day"), t))
for t in monthdays)
# Compose the djano.db.models.Q objects together for a single query.
query = reduce(operator.or_, (Q(**d) for d in monthdays))
# Run the query.
return Person.objects.filter(query)
But it get a list of persons that have a birthday in date range. You should change a bit.