I have a code :
def set_date_range_filter(self,attribute = None,start_date = None , end_date = None):
if attribute is None:
return
#Make sure set the passing start date and end date
if not start_date or not end_date :
return
if isinstance(start_date, str) :
start_date = datetime.strptime(start_date, "%Y-%m-%d")
if isinstance(start_date, unicode) :
start_date = datetime.strptime(str(start_date), "%Y-%m-%d")
if isinstance(end_date ,str):
end_date = datetime.strptime(end_date, "%Y-%m-%d")
if isinstance(end_date ,unicode):
end_date = datetime.strptime(str(end_date), "%Y-%m-%d")
# Shphnx Range Filter ,start_date and end_date must be integers that define the acceptable attribute values range
start_date = int(time.mktime(start_date.timetuple()))
end_date = int(time.mktime(end_date.timetuple()))
if start_date > end_date :
return
self.sphinx.SetFilterRange(str(attribute),start_date,end_date)
I want to update this code to accept only 'start_date' or only 'end_date' or both.
Like i want all date from 2014-01-01 or i want all data after 2014-01-01
or say i want all data from 2014-01-01 to 2014-09-01. how can i archive this ??
Rather than
if not start_date or not end_date :
return
replace with say
if not start_date:
start_date = '1971-01-01'
if not end_date:
end_date = '2037-01-01'
Or similar. If either are missing, then just use a very early, or very late dates (outside the range of your data). Example dates above choosen within range of unix timestamps.
(will then be turned into proper date objects via strptime)
Related
I have a program that scrapes through an API and gets the required values from the fields. There is a field called published_date one act json object. I want to publish only the values for the last 2 months from current date.
try:
price = str(price).replace(',', '')
price = Decimal(price)
if date < end:
if not math.isnan(price):
report_item = PriceItem(
source=SOURCE,
source_url=crawled_url,
original_index_id=original_index_id,
index_specification=index_specification,
published_date=date,
price=price.quantize(Decimal('1.00'))
)
yield report_item
except DecimalException as ex:
self.logger.error(f"Non decimal price of {price} "
f"found in {original_index_id}", exc_info=ex)
The published date is extracted:
for report_date in REPORT_DATE_TYPES:
if report_date in result:
date = result[report_date].split(' ')[0]
date = datetime.strptime(date, '%m/%d/%Y')
MAX_REPORT_MONTHS = 3
current_date = datetime.now()
current_date_str = current_date.strftime('%m/%d/%Y')
start = datetime.strptime(current_date_str, '%m/%d/%Y')
last_date = current_date - relativedelta(months=MAX_REPORT_MONTHS)
last_date_str = last_date.strftime('%m/%d/%Y')
end = datetime.strptime(last_date_str, '%m/%d/%Y')
The above I say last date string and current date string.
Extract of the api:
After having gathered the data into a dataframe you can convert the column containing the dates to datetime and then through comparison operators mantain just the desidered data.
For example, assuming this is your data:
data = {'date': ['02/02/2022 10:23:23', '09/23/2021 10:23:23', '02/01/2021 10:23:23', '12/15/2021 10:23:23'], 'random': [324, 231, 213, 123]}
df = pd.DataFrame(data)
# convert date column to datetime
df['date'] = pd.to_datetime(df['date'], format="%m/%d/%Y %H:%M:%S")
# select "threshold" date, two months before current one
current_date = datetime.now()
last_date = current_date - relativedelta(months=2)
# select data published after last_date
df[df['date'] > last_date]
If we consider the date of today we will have this result.
Before:
date random
0 02/02/2022 10:23:23 324
1 09/23/2021 10:23:23 231
2 02/01/2021 10:23:23 213
3 12/15/2021 10:23:23 123
After:
date random
0 2022-02-02 10:23:23 324
3 2021-12-15 10:23:23 123
What i'm trying to do is to add one extra day to today's date and have the outcome match this formula "%Y-%m-%d" and nothing else. I want the printed results to match this yyyy-mm-dd
from datetime import datetime, timedelta, date
s = date.today()
date = datetime.strptime(s, "%Y-%m-%d")
modified_date = date + timedelta(days=1)
datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)
You are trying to do date operations on strings and not using the result of your formatting call:
s = date.today()
modified_date = s + timedelta(days=1)
modified_date = modified_date.strftime("%Y-%m-%d") # this would be more common
# modified_date = datetime.strftime(modified_date, "%Y-%m-%d")
print(modified_date)
I am trying to build a condition where the store has a s_start_date and s_end_date.
The employee working for the store also has a start_date and end_date.
Let's assume:
Case1------------
store_name: store 1
s_start_date = 12/01/2019, s_end_date = 12/30/2019
Employee_name: Emp1
start_date = 12/01/2019, end_date = 12/20/2019 #Required result
start_date = 11/01/2019, end_date = 01/20/2020 #It should throw an error as the dates are out of store contract.
case 2-----------------
The condition here is that only one employee is needed at a single store
store_name: store 1
s_start_date = 12/01/2019, s_end_date = 12/30/2019
Employee_name: Emp1
start_date = 12/01/2019, end_date = 12/20/2019 #Required result
Employee_name: Emp2
start_date = 12/21/2019, end_date = 12/30/2019 #Required result
start_date = 12/05/2019, end_date = 12/17/2019 #Should throw an error saying that employee already exist for the time frame or dates not available
Please find the attached code for your reference .
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class wv_location(models.Model):
_name= "wv.location"
storel_name = fields.Char(string="Store Name")
s_start_date = fields.Date('Store Start Date', required=True, index=True)
s_end_date = fields.Date('Store End Date', constrains="_check_date")
emp_loc_id = fields.One2many('wv.emp.location', 'employee_loc_id', string="Employees")
#api.constrains('s_start_date','s_end_date')
def _check_date(self):
if self.s_start_date > self.s_end_date:
raise ValidationError('End date must be greater than start date')
class wv_emp_location(models.Model):
_name = "wv.emp.location"
employee_id = fields.Many2one('hr.employee', 'Employee', ondelete='cascade')
employee_loc_id = fields.Many2one('wv.location', 'Employee Location', ondelete='cascade')
start_date = fields.Date('Start Date', tracking=True)
end_date = fields.Date('End Date', tracking=True)
#api.constrains('start_date','end_date')
def _check_date(self):
if self.start_date > self.end_date:
raise ValidationError('End date must be greater than start date')
Please let me know if you need more information on this. I know I can use loops and lists but not sure of how to use for these conditions and not sure of logic.
Thank you
I would like to get rows from specified date range, but when limiter is None (beg_date==None, fin_date==None) I want to ignore scope on one side.
For instance:
If beg_date=='2019-10-23' and fin_date==None I would like to get
rows from 2019-10-23 up to date.
How can I achieve that using SQLAlchemy?
Model:
class MyModel(Model):
date = Column(Date)
Code:
beg_date = some_dict.get('beg_date')
fin_date = some_dict.get('fin_date')
session.query(MyModel).filter(MyModel.date.between(beg_date, find_date)
You could build your date condition with Python conditions on start_date and end_date before building your whole query:
if start_date and end_date:
date_condition = MyModel.date.between(start_date, end_date)
elif start_date:
date_condition = MyModel.date > start_date
elif end_date:
date_condition = MyModel.date < end_date
else:
date_condition = true() # sqlalchemy.true()
session.query(MyModel).filter(date_condition)
I did not tested it but it should work with potential minor fixes.
How to import a date from view and calculate the number of days remaining for another date?
Here is the solution I tried but it's not working:
class saisir_soumi(osv.osv):
_name='saisir.soumi'
def compa_date(self,cr,uid,ids,args,fields,context=None):
r = {}
date_format = "%D/%M/%Y"
joining_date = 'date_depot'
current_date = '29/04/2016 02:02:02'# current date
d1 = datetime.strptime(joining_date, date_format)
d2 = datetime.strptime(current_date, date_format)
diff = current_date - datetime.date.today()
return diff.days
_rec_name = 'NumOffre'
_columns = {
'NumOffre' : fields.char('N° Offre',required=True),
'organisme_s' : fields.char('Organisme',required=True),
'date_depot' : fields.datetime('Date dépot de soumission'), # the date to be seized and used for its difference with current date( today)
'jrestant': fields.function(compa_date,string='Jours restant')
}
_sql_constraints = [
('uniq_NumOffre', 'unique(NumOffre,id)', "numero offre doit resté unique !"),
]
you have to do it properly:
specify correct date/time format
parse datetime from string
substract the same data types: datetime - datetime
Code:
In [68]: current_date = '29/04/2016 02:02:02'
In [69]: date_format = '%d/%m/%Y %H:%M:%S'
In [70]: (datetime.datetime.strptime(current_date, date_format) - datetime.datetime.now()).days
Out[70]: 5