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})
Related
I am writing an app in Django where I have created a PayPeriods model as such:
class PayPeriods(models.Model):
first_day = models.DateField(default=date.today)
last_day = models.DateField(default=date.today)
pay_day = models.DateField(default=date.today)
I've created a small function that allows me to get the current PP through my app,
def get_pp():
_pp = PayPeriods.objects.filter(first_day__gte=datetime.today(),last_day__lt=datetime.today())[0]
return _pp
but its not returning as expected.
What am I missing?
Current day today is 11/29/2022, so I am expecting to return Obj #4, as the code is written.
PP Object #3: first_day = 11/13/22, last_day = 11/26/22
PP Ojbect #4: first_day = 11/17/22, last_day = 12/10/22
PP Ojbect #5: first_day = 12/11/22, last_day = 12/24/22
I have verified that my dates are formatted the same way, (stored data & datetime.today(), and my timezone settings are correct.).
For the node 'TransactionDate' i have a logic before updating it for policy"POL000002NGJ".
The logic i am trying to implement is If existing 'TransactionDate' < than today, then add 5 days with current value and parse it to xml.
Transaction Date Format in XML : 2020-03-23T10:56:15.00
Please Note that, If i parsing the DateTime value like below, It works good But i dont want to hardcode the value... I want to Parse it as a string object to handle for any datetime in format ""%Y-%m-%dT%H:%M:%S.%f""...
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = '2020-03-24T10:56:15.00'
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
Below code while parsing it as a DateTime Object, I have an issue.. I got struck here and referenced other answers in stackoverflow and python forums, But still i got struct up here and unable to resolve the issue...
if any help to fix will be a great helpful. Thanks. Below code using lxml and getting help to support below code will helpful. Because i already completed for other nodes. My understanding is Date variable is calling as None.. But struck here to fix.. Please help..
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = str(TransactionDate)
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
Full Code is Below
from lxml import etree
from datetime import datetime, timedelta
import random, string
doc = etree.parse(r'C:\Users\python.xml')
# <PolicyId> - Random generated policy number
Policy_Random_Choice = 'POL' + ''.join(random.choices(string.digits, k=6)) + 'NGJ'
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.find('TransactionDate')
Date = str(TransactionDate)
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
if previous_update < today:
today = previous_update - timedelta(days=-5)
TransactionDate = today.strftime("%Y-%m-%dT%H:%M:%S.%f")
#Parsing the Variables
replacements = [Policy_Random_Choice , TransactionDate ]
targets = doc.xpath('//ROW[PolicyId="POL000002NGJ"]')
for target in targets:
target.xpath('./PolicyId')[0].text = replacements[0]
target.xpath('.//TransactionDate')[0].text = replacements[1]
print(etree.tostring(doc).decode())
Sample XML
<TABLE>
<ROW>
<PolicyId>POL000002NGJ</PolicyId>
<BusinessCoverageCode>COV00002D3X1</BusinessCoverageCode>
<TransactionDate>2020-03-23T10:56:15.00</TransactionDate>
</ROW>
<ROW>
<PolicyId>POL111111NGJ</PolicyId>
<BusinessCoverageCode>COV00002D3X4</BusinessCoverageCode>
<TransactionDate>2020-03-23T10:56:15.00</TransactionDate>
</ROW>
</TABLE>
Maybe the find method is wrong. Try this one
# <TransactionDate>
today = datetime.now()
TransactionDate = doc.xpath('//ROW/TransactionDate') # Change find to xpath
Date = str(TransactionDate[0].text) # Use the first one
previous_update = datetime.strptime(Date, "%Y-%m-%dT%H:%M:%S.%f")
Good evening, could you help me in how I can put a condition so that a message comes out saying that you can not take an hour because it is already busy ?, I currently have this:
class reserva (models.Model):
_name='gimnasio.reserva'
tipo_reserva=fields.Selection([('clase','Clase'),('evaluacion','Evaluacion')])
fecha_reserva=fields.Date()
start_time=fields.Float()
end_time=fields.Float()
def fecha(self):
if self.star_time==self.star_time:
raise validationError('the hour is busy')
I have another question for you. you know how to configure Datetime only for hour and minutes because I only need hour and minutes but not the date.
To configure Datetime only for hour and minutes.
time = fields.Datetime("time")
custom_time = fields.Char('my_custome_time')
#api.onchange('time')
def _get_time(self):
if self.time:
for rec in self:
# datetime value is a string like 'YYYY-mm-dd HH:MM:SS'
# so just extract string from position 11 to 16
_time = self.time[11:16]
self.custom_time = _time
rec.custom_time = self.custom_time
I think you can use strptime method from datetime module.
from datetime import datetime as dt
start_time = fields.Float()
end_time = fields.Float()
#api.onchange('start_time','end_time')
def _check(self):
records = self.env["gimnasio.reserva"].search([("day", '=', the day you want to check eg. "2019-06-13")])
for rec in records:
ref_start = dt.strptime(str(rec.start_time), "%H:%M")
curr_start = dt.strptime(str(self.start_time), "%H:%M")
if ref_start == curr_start:
raise validationError('the hour is busy')
I didn't debug yet, you can try it.
how to eliminate the default date that you added ("2019-06-13") and that any date should not have the same busy schedule?
In this case you don't need datetime module just
#api.constrains("start_time")
def _check(self):
# search db for any record have same start time.
records = self.env["gimnasio.reserva"].search([('start_time ','=', self.start_time)])
if len(records) > 0:
raise validationError('the hour is busy')
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)
Say I have a model:
Mymodel(models.Model):
endtimestamp = models.DateTimeField(null=True)
I need a query to get all Mymodel objects with endstimestamp between today's midnight and yesterday midnight.
what have I tried:
today = datetime.datetime.today()
todays_midnigh = datetime.datetime.fromtimestamp(
today.strftime('%Y-%m-%d 00:00:00.0')
)
yesterday_midnight = todays_midnight - datetime.timedelta(days=1)
objs = Mymodel.objects.filter(endtimestamp__range(
yesterday_midnight, todays_midnight)
)
But this line todays_midnigh = datetime.datetime.fromtimestamp(today.strftime('%Y-%m-%d 00:00:00.0')) does not work, and I know there must be a much pythonic and clear way of achieving this.
assumming this from datetime import datetime as dt, do that:
today = dt.today()
todays_midnigh = dt.combine(today,dt.max.time())
or
todays_midnigh = dt.combine(today,dt.min.time())
as appropriate