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:
....
Related
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')
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 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)
So I am trying to create a function that checks whether or not the contents of a function is true:
def command_add(date, event, calendar):
'''
Add event_details to the list at calendar[date]
Create date if it was not there
:param date: A string as "YYYY-MM-DD"
:param event: A string describing the event
:param calendar: The calendars database
:return: a string indicating any errors, "" for no errors
'''
>>> calendar == {'2015-10-20': ['Python']}
True
>>> command_add("2015-11-01", "Computer Science class", calendar)
''
How would I write such a function? The problem I'm having is how to make the string or how to see if the string for the date is in the format 'YYYY-MM-DD'.
The following code uses strptime to parse the date, if the parsing fails it is not a proper date string. Then it checks if the date is already in the calendar dict or not to see whether to append or add the first entry.
from datetime import datetime
def command_add(date, event, calendar):
'''
Add event_details to the list at calendar[date]
Create date if it was not there
:param date: A string as "YYYY-MM-DD"
:param event: A string describing the event
:param calendar: The calendars database
:return: a string indicating any errors, "" for no errors
'''
try:
datetime.strptime('%Y-%m-%d', date):
except ValueError:
return 'Error parsing date'
else:
if date in calendar:
calendar[date].append(event)
else:
calendar[date] = [event]
return ''
Look at: https://docs.python.org/2/library/time.html#time.strptime
Give strptime the wanted format and if string is not formatted as you wanted you will get an exception
from datetime import datetime
def command_add(date, event, calendar):
# Your Code
calendar = {'2015-10-20': ['Python']}
try:
Date = "2015-11-01"
date_object = datetime.strptime(Date, '%Y-%m-%d')
command_add(Date, "Computer Science class", calendar)
except:
print "Date Format is not correct"