NSPredicateEditor: filter for month in NSDate object - nsdate

How can I filter a NSDate object by month with NSPredicateEditor ?
I have created a separate predicate editor row template for month.
Then Key Path is set to "myDate.month" and a right expression as numbers. That doesn't work, it tells that myDate.month is not KVO compliant. I have no idea how to use DateComponents in the key path either.
Of course, I could enrich my data model to an attribute "month" and then filter for it. But it is not very elegant and it means to maintain date and month for any updates at the same time..

Related

Python. Best way to filter array by date

I have a list of Rest objects. It's django model
class Rest(models.Model):
product = models.ForeignKey('Product', models.DO_NOTHING)
date = models.DateTimeField()
rest = models.FloatField()
I want to select objects from it for today's date. I do it like this. Maybe there is some more convenient and compact way?
for rest in rests_list:
if rest.date.day == datetime.now().day:
result.append(rest)
First - datetime.now().day will get you the day of the month (e.g. 18 if today is 18th March 2020), but you've said you want today's date. The below is on the assumption you want today's date, not the day of the month.
(NOTE: weAreStarDust pointed out that the field is a DateTimeField, not a DateField, which I missed and have updated the answer for)
The way you are doing it right now seems like it might be fetching all of the Rests from the database and then filter them in your application code (assuming rests_listcomes from something likeRest.objects.all()`. Generally, you want to do as much filtering as possible on the database query itself, and as little filtering as possible in the client code.
In this case, what you probably want to do is:
from datetime import date
Rest.objects.filter(date__date=date.today())
That will bring back only the records that have a date of today, which are the ones you want.
If you already have all the rests somehow, and you just want to filter to the ones from today then you can use:
filter(lambda x: x.date.date() == date.today(), rests_list)
That will return a filter object containing only the items in rests_list that have date == date.today(). If you want it as a list, rather than an iterable, you can do:
list(filter(lambda x: x.date.date() == date.today(), rests_list))
or for a tuple:
tuple(filter(lambda x: x.date.date() == date.today(), rests_list))
NOTE:
If you actually want to be storing only a date, I would suggest considering use of a DateField (although not if you want to store any timezone information).
If you want to store a DateTime, I would consider renaming the field from date to datetime, or started_at - calling the field date but having a datetime can be a bit confusing and lead to errors.
As docs says
For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.
from datetime import datetime
Rest.objects.filter(date__date = datetime.now().day)
You can use the django filter for filtering and get only today's date data from your model. No need to fetch all data first and then apply loop for get today's date data. You have to write your query like ...
import datetime
Rest.objects.filter(date__date = datetime.date.today())
But be sure that timezone should be same for database server and web server

Spotfire- limiting Information link colum expression

I have a column of data [Sales ID] that bringing in duplicate data for an analysis. My goal is to try and limit the data to pull unique sales ID's for the max day of every month in the analysis only (instead of daily). Im basically trying to get it to only pull in unique sales ID values for the last the day of every month in the analysis ,and if the current day is the last day so far then it should pull that in. So it should pull in the MAX date in any given month. Please how do i write an expresion with the [Sales ID] column and [Date ] column to acieve this?
Probably the two easiest options are to
1) Adjust the SQL as niko mentioned
2) Limit the visualization with the "Limit Data Using Expression" option, using the following:
Rank(Day([DATE]), "desc", Month([DATE]), Year([DATE])) = 1
If you had to do it in the Data on Demand section (maybe the IL itself is a usp or you don't have permission to edit it), my preference would be to create another data table that only has the max dates for each month, and then filter your first data table by that.
However, if you really need to do it in the Data on Demand section, then I'm guessing you don't have the ability to create your own information links. This would mean you can't key off additional data tables, and you're probably going to have to get creative.
Constraints of creativity include needing to know the "rules" of your data -- are you pulling the data in daily? Once a week? Do you have today's data, or today - 2? You could probably write a python script to grab the last day of every month for the last 10 years, and then whatever yesterday's date was, and throw all those values into a document property. This would allow you to do a "Values from Property".
(Side Note: I want to say you could also do it directly in the expression portion with something like an extremely long
Date(DateTimeNow()),DateAdd("dd",-1,Date(Year(DateTimeNow()), Month(DateTimeNow()), 1))
But Spotfire is refusing to accept that as multiple values. Interestingly, when I pull the logic for a StringList property, it gives this: $map("${udDates}", ","), which suggests commas are an accurate methodology, but I get an error reading "Expected 'End of expression' but found ','" . Uncertain if this is a Spotfire issue, or related to my database connection)
tl;dr -- Doing it in the Data on Demand section is probably convoluted. Recommend adjusting in SQL if possible, and otherwise limiting in the visualization

Fetch Unique Calendar Dates For Core Data Object

How do we fetch unique Calendar Dates for Core Data Objects?
For example:
If we have three emotion objects with NSDates:
"2014-08-04 20:33:42 +0000",
"2014-08-04 20:50:33 +0000",
"2014-08-04 20:50:46 +0000",
"2014-08-06 20:35:58 +0000",
"2014-08-08 20:33:49 +0000"
I want to get an array of NSDates that looks like this:
2014-08-04
2014-08-06
2014-08-08
I have explored these threads as possible solutions but neither of them work.
CoreData get distinct values of Attribute
How to count unique dates of CoreData objects?
A possibility would be to make time and date attributes for the managed objects I am searching for but that seems like a clunky work around.
Another possibility is to strip the time component of the all the NSDates that come back then filter the array of Dates again for duplicates. Again this seems really clunky and prone to breaking.
I want to get an array of NSDates with only the calendar date and then use that information to present tableview cells. When the user taps a given tableView cell I can push a viewController that displays data related to that calendar date. As time goes on the number of NSDates could get large because there will be many objects with NSDates to search for so the solution should be efficient.
You're going to have to use an approach like the ones you describe, because that's how it needs to be done.
You're storing NSDate values, but NSDate doesn't actually represent a date-- it represents a specific moment in time, to the fraction of a second (it might have been better if it were called something like NSDateTime, but it wasn't). It's really an object wrapper around an NSTimeInterval, which is just a double. Core Data just saves this value, automatically converting to/from NSDate when necessary. As a result, you don't actually have unique calendar dates in your sample data. The time of day is different, which means each of your sample values represents a different double value in the persistent store.
If you want unique date values, you need to either add a field that encodes only the date, or to fetch all of the NSDate style attributes and filter the result. I'd probably go with the first-- store the data you actually need to look up-- but either will work.

Breaking up a Core Data Date Attribute - Good idea?

I am learning Core Data, and I have a project up and running that stores, creates, retrieves, updates, and deletes entities just fine. I am loving using Core Data so far.
I have a simple entity that has 5 attributes. One of them is a date. I call it dateCreated. I am using a TabBar in my app and I want to be able to sort things on different screens by Year and Month, and Month details. I have a couple questions about what is good practice and what is good for performance sake.
So ideally I want my Collection View to be sectioned by Year, and each cell containing a month that takes them to that months table. Currently in one of my tabs have a UITableView that loads user created data but I haven't broken it up by Year and Month yet. Meaning they can just keep putting in dates and other info and the one table just keeps getting larger. I would love to use the Date Attribute my - dateCreated attribute to break the table into multiple tables for each month in my Collection View. It seems like all the data is in place to minipulate and display it anyway I want, but I am not sure if it is the best way to go, or even if it is the standard practice when using Core Data. I would think I could use the same table to load the data based on what year and month it is. Instead of making multiple tables of months.
My questions as long winded as they are: Should I create more Date attributes or use the dateCreated that is displayed in my TableView using a formatter to show it as "Jul, 31 2013". In other words can I break up the user created data based off of my dateCreated attribute alone.
Second. I understand how to "fetch" data from the Core Data stack and get it in the TableView using NSFetchedResutsController, but what if I want to display certain attributes from an entity in a screen that doesn't have contain a table view. Should I still use NSFetchedResultsController, or should I be using something else? The Apple Docs on Fetching Data shows how to fetch specific attributes from the entity to be displayed but it seems like so much code for something so simple that I think I have looked in the wrong section.
Okay I understand this sounds a bit confusing so I am wanting to know if I should use my dateCreated attribute to break up the data, or create more Date attributes one for year, one for month and keep the one for dateCreated and sort it that way. Also if I just want to display certain attributes data without a table on screen should I still be using NSFetchedResultsController?
Thanks for all your help if you provide any. I am having a great time learning Core Data. It is really powerful.
You might want to adjust your predicate for the fetching to something like:
NSDate *startDate = ....;
NSTimeInterval length;
[[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit
startDate:&startDate
interval:&length
forDate:startDate];
NSDate *endDate = [startDate dateByAddingTimeInterval:length];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(eDate >= %#) AND (eDate < %#)", startDate, endDate];

saving a to-many-relationship

I'm starting to learn and practice some CoreData, with no programming experience.
After searching in Web, looking for Apple samples and reading some books, I´m still stucked in one point.
I have two entities (Expenses and Month) with reciprocal relationships called "monthsOfExpense" and "expensesOfmonth" and I'm showing in a tableView the expenses of a single month.
My problem is to insert new expenses and save them: I've a view to insert new expenses where the user can insert the name of Expense, the value and the months that expense is valid (associated with the monthsOfExpense relationship, i hope).
I'm ok saving the name and the value of Expense entity, taking the string and NSDecimal number from the textFields.
My problem is how to associate that expense to a particular or several months? How can I save a textField.text as a relationship, indicating to what month an Expense belongs?
I'm starting with a textField where the user can insert a month, assuming that an Expense is valid for one month only (for learning purposes and simplification).
My idea is to allow the user to select several months (using maybe another tableView with selectable months) and association of an Expense to different months.
I know that a relationship comes as a NSSet, but I'm not being competent to save the attributes and the relationship from a View, at the same time.
Hope was cleared and many thanks in advance for trying to help.
OK. In Core data, you define your "Expense" entity, create a relationship to "Month" entity. Now create class files for these 2 entities. Then you use it by
Expense *expense1 = [NSEntityDescription insertNewObjectForEntityName:#"Expense" ....
Month *month1 = [context executeFetchRequest:......];
expense1.month = month1;
...
[context save];
In your situation, you can predefine 12 "Month" objects, giving the month name as the text property.
Then you can lookup these month objects using NSFetchRequest. Add the relevant month objects to your expense using
[expense addMonthObject:month]
Then save your managed object context.
You message the managed object for its mutableSetValueForKey:RelationshipKey,
then you add the to-many managed objects to that set. CoreData completes the other half of the relationship data.

Resources