I am trying to pass a date into Oracle 2 different ways when running Python code.
Be able to pull the first day of last month and the last day of last month automatically from datetime.date. I found this code online, but not sure that it will produce the first day of last month and the the last day of last month.
import datetime
today = datetime.date.today()
first = datetime.date(day=1, month=today.month, year=today.year)
lastMonth = first - datetime.timedelta(days=1)
In case of situations that I will need to manually enter the date for prior dates, etc. I want to be able to manually enter a beginning and end date. First off is there a way to have Python prompt me to enter start date and end date? Secondly, I can't seem to get my code to work correctly when I try to put the dates in my code.
Import dateutil.parse
start = dateutil.parser.parse('06/01/2015')
end = dateutil.parser.parse('06/30/2015')
startdate = start.strftime('%d-%b-%y')
enddate = end.strftime('%d-%b-%y')
cursor = con.cursor()
cursor.execute(SELECT * From Executives WHERE DateAdded >= %s And DateAdded <= %s), (startdate, enddate)
I have even tried DateAdded >= :s and DateAdded <= :e. but I am still getting an error.
Related
I have a simple if Statement in Power Query I feel I need a separate set of eyes on.
I am trying to say if the current day of the week is Monday then I want the system to display whatever the date was 3 days ago, else any other day just show yesterdays date. My formula below is receiving the error "Token RightParen expected." at the "Date" after "then" on the 2nd line.
if(Date.DayOfWeek(DateTime.FixedLocalNow()) = 0 then
Date.AddDays(Date.From(DateTime.FixedLocalNow()),-3) else
Date.AddDays(Date.From(DateTime.FixedLocalNow()),-1))
A few extra characters. Remove first and last parenthesis
let Source = if
Date.DayOfWeek(DateTime.FixedLocalNow()) = 0 then
Date.AddDays(Date.From(DateTime.FixedLocalNow()),-3) else
Date.AddDays(Date.From(DateTime.FixedLocalNow()),-1)
in Source
A bit of a naive question. I want to create a dataframe that spans a full calendar year in hourly resolution (8760 values). How can I manipulate the following lines from a tutorial to pull data from the previous year.
start = pd.Timestamp(datetime.date.today(), tz=time_zone) #used for testing
end = start + pd.Timedelta(days=365) #to get all day values
Essentially I want to replace today() with 1/1/2016, and then pull historical forecasted values for my analysis.
You can build start by subtracting a year from whatever your end date is:
date_str = '1/1/2016'
start = pd.to_datetime(date_str) - pd.Timedelta(days=365)
hourly_periods = 8760
drange = pd.date_range(start, periods=hourly_periods, freq='H')
Then when you're ready to make a data frame, set index=drange, e.g.:
# toy example data
data = list(range(len(drange)))
# create data frame with drange index
df = pd.DataFrame(data, index=drange)
See Pandas docs for date_range and Timedeltas for more.
I need to write django raw query for filtering year and month. for that I have tried following code.
cursor = connection.cursor()
cursor.execute('SELECT SUM(work_time) AS sum FROM structure_tracking_details WHERE employee_id = %s AND tree_id=%s AND project_structure=%s AND year(date)=%s AND month(date)=%s GROUP BY project_structure ', [employee_id,tree_id,project_structure,select_year,select_month] )
sum1=str(cursor.fetchone())
but it tells no such function: year what's wrong with my code?
SQLite doesn't have a YEAR() function. If you want year, you can use something like this -
select strftime('%Y', datetime(datefield, 'unixepoch')) as year from table_name
So instead of writing year(date)=%s, you could write strftime('%Y', date) = %s. It should work. I haven't tried it.
Or leave all these headache and use Django's ORM. You should be using that at the first place.
Edit:
According to OP, this query worked -
cursor.execute("SELECT SUM(work_time) AS sum FROM structure_tracking_details WHERE employee_id = %s AND tree_id=%s AND project_structure=%s AND strftime('%%Y', date) = %s AND strftime('%%m', date) = %s GROUP BY project_structure ", employee_id, tree_id, project_structure, select_year, select_month])
The %Y needed to be escaped using %%Y.
Why don't you use the ORM?
If you have a model like this:
class Work(models.Model):
date_field = models.DateField()
# your other fields
You can do this query using the year and month lookups:
Work.objects.filter(date_field__year=2013,date_field__month=2)
Now, to add the rest of your stuff, which is the summing of work_time and group by:
from django.models import Sum
Work.objects.filter(date_field__year=2013,
date_field__month=2,
employee_id=1,
...).values('project_structure').aggregate(total=Sum('work_time'))
Does anyone know how I can sort (in this instance date) my django query set against todays date ?
class Person(models.Model):
name = models.CharField(max_length=50)
date = models.DateField()
My goal is to list the name and date entries. At the top of the list will be the entry with the date that is closest to todays date (day/month).
You can use extra queryset method to select additional data from database table.
This is example that works with MySql:
Person.objects.extra(select={
'datediff': 'ABS(DATEDIFF(date, NOW()))'}).order_by('datediff')
DATEDIFF - returns difference in days bewteen two dates,
ABS - returns absolute value. For sqlite, there is different syntax, see this answer.
EDIT: use current year
Person.objects.extra(select={
'datediff': "ABS(DATEDIFF(CONCAT(YEAR(now()), '-', MONTH(date), '-', DAY(date)), NOW()))"}
).order_by('datediff')
EDIT 2: optimized *
from datetime import date
dayofyear = int(date.today().strftime("%j"))
datediff = 'LEAST(ABS(DAYOFYEAR(date) - %d), ABS((366 - %d + DAYOFYEAR(date))) MOD 366)' % (
dayofyear, dayofyear
)
Person.objects.extra(select={'datediff': datediff}).order_by('datediff')
EDIT 3: closest date after given (todays) date
from datetime import date
dayofyear = int(date.today().strftime("%j"))
datediff = '(DAYOFYEAR(date) - %d + 365) MOD 365' % (
dayofyear
)
Persion.objects.extra(select={'datediff': datediff}).order_by('datediff')
If you want to sort based on date, you can order as: .order_by('date') on a result queryset.
I'm not sure if that answers your question. In case you mean you want to select only the Persons with date of today, you can use:
import datetime
now = datetime.datetime.now()
persons_with_date_today = Person.objects.filter(date=now)
I am using a QCalendarWidget in my application, and I overloaded the updateCells method to put a red background on every dates which meet certain conditions.
My problem is I don't know how to get the first date displayed in the calendar (not the first date in the month), and the last date displayed.
Example: in february, the first date displayed is january the 25th, and the last date displayed is march the 7th.
There isn't any useful method in QCalendarWidget and I can't think of an algorithm for this.
Do you have any idea how to do this ?
As you've got access to the currently shown month and year, you can use the QDate::dayOfWeek on the first and last date of the shown contents. Taking QCalendarWidget::firstDayOfWeek into account, you aught to be able to decide how far back and forth you have to go.
QCalendarWidget class is a combination of more simple widgets, you can see Qt source code for help. Just use loop to get all dates between:
class myQCalendar(QCalendarWidget):
"""custum QCalendarWidget"""
def __init__(self, parent=None):
self.table = self.findChild(QTableView)
def return_first_last_dates(self) -> Tuple[QDate, QDate]:
# first row(0) and col(0) - headers, so we use second(1,1)
first_date = self.date_by_index(
self.table.model().index(1, 1))
last_date = self.date_by_index(
self.table.model().index(6, 7))
return first_date, last_date
# self.table.model().dateForCell(1,1) didn't work in python
# maybe it will work in c++
def date_by_index(self, index: QModelIndex) -> QDate:
""" Return QDate by index of model of QTableView """
date = self.selectedDate()
day = int(index.data())
mnth = date.month() # current month always the same as current date
if day > 15 and index.row() < 3: # qcalendar always display 6 rows( and 0 - is header)
mnth = date.month() - 1
if day < 15 and index.row() > 4:
mnth = date.month() + 1
return QDate(date.year(), mnth, day)