Would MongoDB take a datetime object with missing fields? - mongodb

Right now I have a datetime object, but it doesn't contain all the fields. It's missing minutes, seconds, and microseconds. I want to use this to fetch data from MongoDB through Python. i'm just wondering if pymongo will automatically fill in the missing fields and convert it into ISODATE, or it's going to produce an error?
EDIT:
an example:
time1='2015-12-17 23'
#assuming already imported all necessary libs
time2=datetime.strptime(time1, '%Y-%m-%d %H')
#for mongo
sq = {'$and': [something.some, {'field1':{'ne':1}}]}
sq['$and'].append({'field2': {'$gt': time2}})

In python, there's no such thing as a datetime object with missing fields. All the datetime fields (relevant to this question) always have values.
The way you created time2, the fields you didn't specify get the value 0, as demostrated here:
% time2
=> datetime.datetime(2015, 12, 17, 23, 0)
% time2.minute, time2.second, time2.microsecond
=> (0, 0, 0)
time2 == datetime(2015, 12, 17, 23, 0,0,0)
=> True
As demostrated above, your time2 object is identical to the object you would have gotten if were manually filling the values with zeros.
Now that you see your datetime object is not missing anything, it should be clear how mongodb treats it.

Related

How do i get datetime into a tableau extract with pantab

I have this code:
import pantab
import pandas as pd
import datetime
df = pd.DataFrame([
[datetime.date(2018,2,20), 4],
[datetime.date(2018,2,20), 4],
], columns=["date", "num_of_legs"])
pantab.frame_to_hyper(df, "example.hyper", table="animals")
which causes this error:
TypeError: Invalid value "datetime.date(2018, 2, 20)" found (row 0 column 0)
Is there a fix?
This has apparently been a problem since time 2020. You have to know which columns are datetime columns because panda dtypes treat dates and strings as objects. There's a world where data scientists don't care about dates, but not mine, apparently. Anyway, here's the solution awaiting the day when pandas makes the date dtype:
[https://github.com/innobi/pantab/issues/100][1]
And just to reduce it down to do what I did:
def createHyper(xlsx, filename, tablename):
for name in xlsx.columns:
if 'date' in name.lower():
xlsx[name] = pd.to_datetime(xlsx[name],errors='coerce',utc=True)
pantab.frame_to_hyper(xlsx,filename,table=tablename)
return open(filename, 'rb')
errors = 'coerce' makes it so you can have dates like 1/1/3000 which is handy in a world of scd2 tables
utc = True was necessary for me because my dates were timezone sensitive, yours may not be.
I screwed up the hyperlink, It's not working. Damn it. Thank you to the anonymous editor who will inevitable show up and fix it. I'm very sorry.

How to reduce a list to earliest/latest DateTime items in Dart- you know the fun type of code problem

I have a list of DateTime items, I want to get the earliest and latest items in that list for initializing a date range picker with min/max values based on the available data in db.
I have a tough time tracking the "behind the scenes" in loops and the reduce operator. So I'm looking for any help in making this happen efficiently, cause I'm sure I can make this happen inefficiently with 10 loops :P
What I've tried so far, random stuff that obviously is way off. Double loops and looping with reduce and .isbefore or .isAfter. Can't figure this out. My code below is a hodgepodge but it's where I'm at now. I guess another option is to simple order the list by date and take first and last, but I want to see the best solution and I think this is the right place to ask.
This is what I'm trying to apply.
List<DateTime> dateList = [
DateTime(2021, 7, 30),
DateTime(2021, 6, 25),
DateTime(2021, 5, 14),
DateTime(2021, 4, 2),
DateTime(2021, 3, 12),
DateTime(2021, 3, 21)
];
List<DateTime> databaseDateRange() {
var databaseDateRange = <DateTime>[];
for (var item in dateList) {
dateList.reduce((value, element) {
if (value.isAfter(item)) {
databaseDateRange.add(value.xAxis);
}
});
}
return databaseDateRange;
}
print(dateList.reduce((min, e) => e.isBefore(min)? e : min));
In order to get the minimum in the list (i.e earliest date) you can do as #the38amorim said.
I.e
print(dateList.reduce((min, e) => e.isBefore(min) ? e : min));
The above iterates through each one and checks whether the new value is before the saved one, and replaces it if that is the case, otherwise keeps the old one.
For maximum value in the list (i.e latest date), you can conversely do:
print(dateList.reduce((min, e) => e.isAfter(min) ? e : min));
More on reduce here: https://api.dart.dev/stable/2.18.1/dart-core/Iterable/reduce.html

compare two date value in qlik sense

In qlik sense, there are two fields' (Package_Packing_End_Working_Date, Pkg_Wave_Sum_Working_Date) value i need to compare, if equal, then return 1, if not equal, then return 0, the fields store date value.
So my formula, if(Pkg_Wave_Sum_Working_Date = Package_Packing_End_Working_Date,1,0)
but it all return 0, may i know which part is wrong?
Your dates can have a time that could lead to this behavior. You can try to use daystart function if(daystart(Pkg_Wave_Sum_Working_Date) = daystart(Package_Packing_End_Working_Date), 1, 0)
Qlik have several problems when works with dates. Try to force to be a date:
Date(Pkg_Wave_Sum_Working_Date,'dd/mm/yyyy') and then try to do the if sentence. Other solutions is try to convert into number with following sentence:
Num(Date#(Pkg_Wave_Sum_Working_Date, 'dd/mm/yyyy'))
With this sentece you can compare two number with:
if(
Num(Date#(Pkg_Wave_Sum_Working_Date, 'dd/mm/yyyy'))-
Num(Date#(Pkg_Wave_End_Sum_Working_Date, 'dd/mm/yyyy'))=0,1,0)

Adding days to a date using std.datetime

Why are you not allowed to add days to a date in std.datetime? You can add months and years, but not days.
Recently I had to calculate a date for Easter Sunday, then I had to calculate related holidays (Ascension, Pentecost, Trinity, Corpus) by adding a certain number of days (39, 10, 7, 4) to the last date.
I ended up using dayOfYear:
date.dayOfYear(date.dayOfYear + offset);
This worked well, but only because I remained within the same year. What if I have to add 50 days to, say, dec 28?
Is there an easy way of doing this that I have overlooked?
You can use Duration from core.time.
Importing std.datetime will import core.time, so you can use it directly as follows.
import std.stdio, std.datetime;
void main() {
auto date = Date(2013, 12, 28);
writefln("%s + %s = %s", date, 10.days(), date + 10.days());
}
BTW, days() is an alias to dur!"days"() which constructs a Duration struct.
Check the documentation of core.time http://dlang.org/phobos/core_time.html for more information.
If you haven't read this article on std.datetime yet, then you probably should, as it will probably answer most basic questions that you have for how to use it.
But in general, core.time.Duration is what you should be using for adding and subtracting units from any of the time point types in std.datetime (SysTime, DateTime, Date, or TimeOfDay). So, you get code like
auto date = Date(2012, 12, 21);
date += dur!"days"(50);
or
auto date = Date(2012, 12, 21);
date += days(50);
(The templated dur function is the generic way to generate a Duration, but it has aliases for each of the units that it supports, so stuff like seconds(5) or 22.minutes() will work as well).
The add function exists for "months" and "years", because a Duration can't hold months or years (because you can't convert between them and smaller units without a specific date), and there needs to be a way to add months or years to a time point. Also, there's the question of what to do when you add or subtract a month or year to/from a date, and the month that it moves to doesn't include that day, so add accepts AllowDayOverflow in order to control that (which wouldn't be necessary with smaller units).
auto d3 = Date(2000, 2, 29);
d3.add!"years"(1);
assert(d3 == Date(2001, 3, 1));
auto d4 = Date(2000, 2, 29);
d4.add!"years"(1, AllowDayOverflow.no);
assert(d4 == Date(2001, 2, 28));
But add doesn't accept any other units, because you can simply use the normal arithmetic operations with a Duration. Also, subtracting two time points will result in a Duration.
assert(Date(2012, 12, 5) - Date(2002, 11, 17) == dur!"days"(3671));
assert(Date(2012, 12, 5) - dur!"days"(3671) == Date(2002, 11, 17));
Unlike add, roll accepts all of the units in the type rather than just "months" and "years", but that's because it's doing a different operation from +, and so adding or subtracting a Duration won't work (as that already adds or subtracts). Rather roll adds to a specific unit without adding to the others.
auto d = Date(2010, 1, 1);
d.roll!"days"(33);
assert(d == Date(2010, 1, 3));
You can useroll method:
date.roll!"days"(50);
I did overlook it: you can use dayOfGregorianCal:
import std.stdio, std.datetime;
void main() {
auto d = Date(2012, 12, 28);
writeln(d); // 2012-Dec-28
d.dayOfGregorianCal(d.dayOfGregorianCal + 50);
writeln(d); // 2013-Feb-16
}

date difference and match with value in javascript

Hi I have the Drop down with values as "One year ", "Two year",...etc.. Ok? also i have two ajax textbox with calender extender . I want to popup alert message if dropdown selected value is "One year" and duration between the both textbox value Means dates not matches. getting what i mean ? please help me.
How can i get this scenario in javascript ??
Algorithm :
1.Get the both date from the text box.
2. The find the epcoch time for each date. //
3. subtract the both dates.
4. subtract_result = 365*24*60*60 // Finding the 1 year timestamp values
5. So, it the difference exceed than above calculation , you could sure that the date is mis matching.
Javascript:
// This is for first date
first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((first.getTime())/1000); // get the actual epoch values
second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
document.write((second.getTime())/1000); // get the actual epoch values
diff= second - first ;
one_day_epoch = 24*60*60 ; // calculating one epoch
if ( diff/ one_day_epoch > 365 ) // check , is it exceei
{
alert( 'date is exceeding one year');
}