I want to query MongoDB and return records that have the date of 12/6/2017. The date is in this format:
u'Date': datetime.datetime(2017, 12, 6, 15, 9, 21, 303000)
So, how do I query just the year, month, and day of that entry? I have tried:
date = db.data.find({ 'Date' : {'2017, 12, 6'} },{'Date' : '1'})
for document in date:
print(date)
Which returns: "InvalidDocument: Cannot encode object: set(['2017, 12, 6'])".
I also tried:
date = db.data.find({ 'Date' : {datetime('2017, 12, 6')} },{'Date' : '1'})
for document in date:
print(date)
Which returns: "NameError: name 'datetime' is not defined".
UPDATE...SOLUTION
I was putting the date into Mongo incorrectly. I'm now putting the date into Mongo with Python like this:
import datetime
import dateutil.parser
# the date
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
theDate = str(year) + "-" + str(month) + "-" + str(day)
dateStr = theDate
date = dateutil.parser.parse(dateStr)
# Then put that date into your Mongo insert
This is how I'm querying by date. This pulls documents inserted after yersterday (today).
import dateutil.parser, datetime
now = datetime.datetime.now()
year = now.year
month = now.month
yesterday = now.day - 1
dateStr = str(year) + "-" + str(month) + "-" + str(yesterday)
date = dateutil.parser.parse(dateStr)
cursor = db.data.find({'Date' : { '$gt' : date}},{'Date':'1'})
for document in cursor:
print(document)
When you say the object is stored as datetime.datetime, to what are you referring? A custom object?
Per the Mongo docs, this is the only date object they support explicity:
https://docs.mongodb.com/v3.4/reference/method/Date/
From the Docs:
Date() Returns a date either as a string or as a Date object.
Date() returns the current date as a string in the mongo shell. new
Date() returns the current date as a Date object. The mongo shell
wraps the Date object with the ISODate helper. The ISODate is in UTC.
You can specify a particular date by passing to the Date() method a
datetime string. For example:
new Date("") which returns the ISODate with the specified
date. new Date("") which specifies the datetime
in local datetime and returns the ISODate with the specified datetime
in UTC. new Date("") which specifies the
datetime in UTC and returns the ISODate with the specified datetime in
UTC.
To create a query to search on a Date field in mongo, you would instatiate an ISODate like this
db.collection.find({"datefield" : ISODate("YYYY-MM-DDTHH:MM:SS")})
Generally, this will be of somewhat limited use, since the time is measured in milliseconds, so you'll likely need to do a range query similar to:
db.collection.find({"datefield" : {"$gte" : <beginning_of_day_as_ISODate>, "$lte" : <end_of_day_as_ISODate>})
For example:
{createdDate : {$gte : ISODate("2017-12-06T00:00:00"), $lte : ISODate("2017-12-06T23:59:59")}}
If you are using a custom date object, or storing the date in some non-standard format, your query will need to be tailored to that object.
You can try out something like this
date = db.data.find({ 'Date' : {new ISODate("2017-12-6T23:59:59Z") } },{'Date' : '1'})
for document in date:
print(date)
Or you could try out this,
date = db.data.find({ 'Date' : {new Date(2017,12,6) } },{'Date' : '1'})
for document in date:
print(date)
Related
I get startdate and enddate, but they are passed as a string. How do I convert them to a date?
startdate = request.POST["startdate"]
enddate = request.POST["enddate"]
queryset = paidparking.objects.all()
qsstats = QuerySetStats(queryset, date_field='expirationdate')
values = qsstats.time_series(startdate, enddate, interval='days')
return render(request, 'index/template.html', {'values': values})
Error in: values = qsstats.time_series(startdate, enddate, interval='days')
startdate and enddate are strings, not datetime objects. You need to parse these, so something like:
from datetime import datetime
startdate = datetime.strptime(request.POST['startdate'], '%Y-%m-%d')
enddate = datetime.strptime(request.POST['enddate'], '%Y-%m-%d')
queryset = paidparking.objects.all()
qsstats = QuerySetStats(queryset, date_field='expirationdate')
values = qsstats.time_series(startdate, enddate, interval='days')
return render(request, 'index/template.html', {'values': values})
The format here ('%Y-%m-%d') might be different, depending on how the date is formatted as string.
I would however advise to work with a Form [Djang-doc]. These forms make it convenient to parse, clean and validate input.
I have to set the date and time available as a string in the following format.
"%Y/%m/%d %H:%M:%S"
cur_time = strftime("%H:%M:%S", gmtime())
cur_date = DATA[1]
date_time = cur_date+" "+cur_time
now = QtCore.QDate.fromString(date_time, '%Y/%m/%d %H:%M:%S')
self.dateTimeEdit.setDate(now)
But this is not working.
The format of date and datetime is different from the format of QDate and QDateTime, you should not use% in the Qt format, check the docs for more detail:
Assuming DATA[1] has a format %Y/%m/%d as you try to use, you can use the following code:
cur_time = strftime("%H:%M:%S", gmtime())
cur_date = "2018/11/10"
date_time = cur_date+" "+cur_time
now = QtCore.QDateTime.fromString(date_time, 'yyyy/M/d hh:mm:ss')
self.dateTimeEdit.setDateTime(now)
Currently the date format on our Odoo CRM looks like 11/20/2017 13:03:41 but I want to display the format to July 3rd 3:00PM and on another place show as 3 Jul 3:00PM
We show this field in the form
<field name="pickup_time"/>
I have searched a lot to find how to change the format, but It's mainly to change in the local settings and it's permanently one setting for everywhere. Which would not solve of what we want, like having two different format for different places.
Along Odoo the default constant date format used is DEFAULT_SERVER_DATETIME_FORMAT. This is defined in the file misc.py
DEFAULT_SERVER_DATE_FORMAT = "%Y-%m-%d"
DEFAULT_SERVER_TIME_FORMAT = "%H:%M:%S"
DEFAULT_SERVER_DATETIME_FORMAT = "%s %s" % (
DEFAULT_SERVER_DATE_FORMAT,
DEFAULT_SERVER_TIME_FORMAT)
So if you declare the field like the following code then that constant is going to be used:
pickup_time = fields.Datetime(
string="Pickup time",
)
So if you want to use another format you can create a computed field with that custom format. You need to use some date functions: strftime (object to string) and strptime (string to object). The formats codes are explained almost at the bottom of this python documentation page
from datetime import datetime
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
[...]
pickup_time_formated = fields.Char( # it is going to be a readonly field
string='Pickup time formated',
compute='_compute_pickup_time_formated'
)
#api.multi
#api.depends('pickup_time')
def _compute_pickup_time_formated(self):
for record in self:
date = record.pickup_time
date_obj = datetime.strptime(date, DEFAULT_SERVER_DATETIME_FORMAT) # to convert it in a date object
v = date_obj.day % 10 # to get the remainder of the operation
if v == 1:
ordinal_suffix = 'st'
elif v == 2:
ordinal_suffix = 'nd'
elif v == 3:
ordinal_suffix = 'rd'
else:
ordinal_suffix = 'th'
# format 'July 3rd 3:00PM'
record.pickup_time_formated = datetime.strftime(date_obj, '%B %d' + ordinal_suffix + ' %I:%M %p')
# format '3 Jul 3:00PM'
# record.pickup_time_formated = datetime.strftime(date_obj, '%d %b %I:%M %p'),
And then you can show the new fields in the xml form:
<field name="pickup_time_formated"/>
I have a pre made Python script that calls a C# script within an address server. The output of this script is:
Build Number : 2381
Database Date : 2015-07-15
Database Expiration Date: 10-31-2015
License Expiration Date : 2016-05-03
Build Number : 2381
Database Date : 2015-06-15
Database Expiration Date: 2015-12-15
License Expiration Date : 2016-05-03
I want to be able to check today's date against the "License Expiration Date". I've looked over datetime and I am stumped. I know I can't check a date against an integer, but I just cant get it. This is what I have so far.
import time
print (time.strftime("%Y-%m-%d"))
datet = '2015-12-15'
class Timedelta(object):
#property
def isoformat(self):
return str()
ExpirationDate = time.strftime("%Y-%m-%d")
if ExpirationDate >= datet:
print 'Renew License Soon'
elif ExpirationDate == datet:
print 'Renew License Immediately'
else:
print "License OK"
quit()
You should be comparing datetime objects using strptime to create the datetime object from your expiration date string and comparing it to datetime.now().date(), strftime creates strings which will be compared lexicographically so you can get incorrect results:
from datetime import datetime, date
datet = '2015-12-15'
ExpirationDate = datetime.strptime(datet,"%Y-%m-%d").date()
now = date.today()
if ExpirationDate >= now:
....
what i wanted to do with this code is get all the datas thats dated older than yesterday. It throws an error "an integer is required" at the line:
date = datetime.date(year, month, yesterday)
So far to my knowledge, its taking year as an integer but not month field. It takes the month field as the default datetime field.
Heres my view:
current = datetime.datetime.now()
yesterday = datetime.datetime.today() + datetime.timedelta(days = -1)
year = datetime.date.today().year
month = datetime.date.today() + relativedelta(months = -1)
date = datetime.date(year, month, yesterday)
hist_obj = Events.objects.filter(uploader = request.user,
start_date__lte = date)
return render_to_response('history.html', {'history_obj':hist_obj})
This code is confusing. yesterday and month are both datetimes, because that's how you defined them in lines 2 and 4. So what are you trying to achieve in the code that throws the error? As the message says, you can't pass a datetime as the day or month parameter to construct another datetime. Especially as, surely, yesterday is already the date that you want? Why can't you simply pass that to the query?
Try this,
day_ago = datetime.date.today() - datetime.timedelta(days=1)
yesterday = datetime.datetime(day_ago.year, day_ago.month, day_ago.day)
hist_obj = Events.objects.filter(uploader = request.user,
start_date__lt = yesterday)
return render_to_response('history.html', {'history_obj':hist_obj})