How to get only date from "Date" field in python - python

def generate_leave(self, cr, uid,ids, fields, context=None):
if context is None:
context = {}
month_split = self.browse( cr, uid,ids)
print "\n\n\n\n\n\n DATEE",month_split.name
dt = datetime.strptime(month_split.name, "%Y-%m-%d")
# date= dt.strftime(month_split.name[],'%Y-%m-%d')
# print "\n\n\n\n\n DAT",date
year = dt.year
print "\n\n\n\n YER",year
month = dt.month
print "\n\n\n MNTH",month
currentMonth = datetime.now().month
print "\n\n\n\n\n CURR MNTH",currentMonth
date = dt.date
print "\n\n\n\n\n\n DATTE",date
date = datetime.now().day
print "\n\n\n\n\n\n DATEE",date
This is my code. I am able to get current date separately. But in my scenario user will input a date and I want to take only the "Date" from that input, I don't want month and year.

Related

Know which parts a day contains

The dateparser library set missing parts of a date to today's values.
Example:
>>> import dateparser
>>> dateparser.parse("2015")
datetime.datetime(2015, 2, 14, 0, 0)
How to know which parts a date really contains?
(and thus which parts were set to today's values by the library)?
This is what I've come up with.
Is there a more efficient way?
date_str = input('Type a date: ')
settings = {"REQUIRE_PARTS": ["year"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
print("Invalid Date")
return
settings = {"REQUIRE_PARTS": ["year", "month"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
print("Date has year only")
return
settings = {"REQUIRE_PARTS": ["year", "month", "day"]}
res = dateparser.parse(date_str, settings=settings)
if res is None:
print("Date has year and month")
return
print("Date has year, month and day")

How to Show Date into words in odoo 12 reports

I am using odoo 12 and want to show Date field record from a model into Reports, how can i do this?
Still facing error
time data 'False' does not match format '%d %B, %Y'
here is my code
#api.multi
def _get_student_dob_in_words(self, student_id):
date_of_birth = fields.Date('BirthDate', default=fields.date.today(),
states={'done': [('readonly', True)]})
student = self.env['student.student'].search([('id','=',student_id)])
date_of_birth = student.date_of_birth
# date_of_birth = date.today()
# %Y-%m-%d %H:%M:%S
strp_date = datetime.strptime(str(date_of_birth),"%d %B, %Y")
# dob_result = datetime.strptime(date_of_birth, DEFAULT_SERVER_DATETIME_FORMAT).date()
# str_dob_result = str(date_of_birth)
strp_dob_result = num2words(strp_date)
strp_dob_result = strp_dob_result.upper()
return [{
'dob_in_words': strp_dob_result}]
You don't need strptime at all, you may use strftime. You still have to test if date is present. And i would make it as computed field as well.
_{name|inherit} = 'student.student'
#date_of_birth = fields.Date(...
date_of_birth_words = fields.Char(compute='_compute_dob_in_words', store=True)
#api.depends('date_of_birth')
def _compute_dob_in_words(self):
for student in self:
if student.date_of_birth:
date_of_birth = student.date_of_birth
month = date_of_birth.strftime('%B') #date_of_birth.month
day = num2words.num2words(date_of_birth.day, to='ordinal')
year = num2words.num2words(date_of_birth.year)
student.date_of_birth_words = "{} {} in year {}".format(day, month, year).upper()

Strftime error Python

I'm calling a function to get the calculation for driver revenue but, I keep getting this error:
"line 396, in driver_get_revenue
monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
AttributeError: 'int' object has no attribute 'strftime'"
The function is this:
def driver_get_revenue(request):
driver = JWTAuthentication().authenticate(request)[0].driver
#Returns the difference between date and time.
from datetime import timedelta
revenue = {}
monthly = {}
yearly = {}
today = timezone.now()
month = today.month
year = today.year
#Created a range to calculate the current weekday.
current_weekdays = [today + timedelta(days = i) for i in range(0 - today.weekday(), 7 - today.weekday())]
for day in current_weekdays:
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = day.year,
created_at__month = day.month,
created_at__day = day.day
)
revenue[day.strftime("%A")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for day in range(0, 30):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__month = month,
created_at__day = day
)
(Line 396) monthly[month.strftime("%m")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
for month in range(0, 12):
orders = Order.objects.filter(
driver = driver,
status = Order.DELIVERED,
created_at__year = year,
created_at__month = month
)
yearly[year.strftime("%y")] = orders.count() * settings.DRIVER_DELIVERY_PRICE
return JsonResponse({"revenue": revenue,
"month": monthly,
"yearly": yearly})
I'm not exactly sure where I went wrong. I marked line 396 so that you see where the error is. Any help will be greatly appreciated.
Thanks.
When you do this: month = today.month, month becomes an integer. The strftime function works with datetime objects, not with integers.
Therefore, month.strftime("%m") doesn't work.
Try day.strftime("%m") instead, or perhaps just month, depending on your requirements.
If instead you're looking for the month's name, you could do it like this:
today = timezone.now()
month = today.month
month_name = today.strftime("%B") # e.g. December
...
...and use the month_name variable in your code.

Slots Creation based on date and time(float) field

I have two date field.
from_date and
to_date
In One2many line item, there is three float fields
from_time ,to_time and interval
Slot have to be created based on the above parameters.
Example:
from_date = '2017-07-21'
to_date = '2017-07-21'
the duration is one day.
The One2many line items have the values
from_time = 9.0
to_time = 10.0
interval = 30(in minutes)
The output should generate two slots
1. '2017-07-21 09:00:00' '2017-07-21 09:30:00'
2. '2017-07-21 09:30:00' '2017-07-21 10:00:00'
It should generate two line items.
If the duration is for week.
it should generate 2 * 7 = 14 slots.
I have used the code which generates for one day.
#api.one
def generate(self):
cr = self.env.cr
uid = self.env.uid
context = self.env.context
event = self.pool.get('calendar.event')
slot = self.pool.get('slot.booking')
old_data_id = slot.search(cr, uid, [('slot_id', '=',self.id)], context=context)
slot.unlink(cr, uid ,old_data_id)
for each in self.shift_line:
if each.interval > 60 or each.interval == 0:
raise osv.except_osv(_('Attention!'), _('Please enter interval timings in minutes range like (10-60) '))
interval = each.interval
fmt = "%Y-%m-%d"
start_date = datetime.strptime(self.from_date, fmt)
end_date = datetime.strptime(self.to_date, fmt)
days = []
date = start_date
pdb.set_trace()
str_start_time = '%s %s' % (self.from_date,'{0:02.0f}:{1:02.0f}'.format(*divmod(each.from_time * 60, 60)))+':00'
str_end_time = '%s %s' % (self.from_date,'{0:02.0f}:{1:02.0f}'.format(*divmod(each.to_time * 60, 60)))+':00'
time = datetime.strptime(str_start_time, '%Y-%m-%d %H:%M:%S')
end = datetime.strptime(str_end_time, '%Y-%m-%d %H:%M:%S')
while date <= end_date:
hours = []
while time <= end:
hours.append(time.strftime("%Y-%m-%d %H:%M:%S"))
time += timedelta(minutes=interval)
date += timedelta(days=1)
time += timedelta(days=1)
end += timedelta(days=1)
days.append(hours)
print "\n\n\n\n\nn\+++++++++++++++++++++days",days
for hours in days[0][:-1]:
val = datetime.strptime(hours, '%Y-%m-%d %H:%M:%S')
val = val + timedelta(minutes=interval)
values = {
'name' : 'Slot for ' + self.employee_id.name,
'start_datetime' : hours,
'stop_datetime' : str(val),
'slot_id' : self.id,
'shift_lines_id' : each.id,
'partner_id': self.employee_id.id,
'duration' : each.interval,
}
print "\n\n\n\n\n\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++values",values
slot.create(cr, uid, values, context=context)
Any help for multiple days is appreciated.
ist_timedelta = timedelta(seconds=((time in seconds)-10800))
adding this will give the exact answer, here 10800 is because of 3 hours difference of UTC to KSA.

change (eg) 8 to 08...python

I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.
For example: sometimes the date element is like 1/1/2011 and sometimes it is like 01/01/2011
Since I am plotting this data later.. this causes a great deal of noise in my plots. The following is my date class. Can you help me out in where and how to modify the code in order to get the date in the form 01/01/2011
import re
class Date:
def __init__(self, input_date):
self._input_date = input_date
self._date = None
self._month = None
self._year = None
self._hour = None
self._min = None
def setDate(self):
date = self._input_date
#date = re.findall('w+',date)
date = self.__mySplit()
#print"len ",len(date)
assert (len(date) >= 3) #has atleast dd/mm/yy
#dateLength = len(date[0])
self._month = int(date[0])
self._date = int(date[1])
self._year = int(date[2])
if (len(date) ==5):
self._hour = int(date[3])
self._min = int(date[4])
def __mySplit(self): #splitting the date by delimiters..
res = [self._input_date]
#print res
seps = [' ','/',':']
for sep in seps:
s,res = res,[]
for seq in s:
res += seq.split(sep)
#print res
return res
Thanks
You definitely want to be using datetime. Here's some code that will get a datetime from either string type:
from datetime import datetime
def strToDatetime(dateStr):
return datetime.strptime(dateStr, "%d/%m/%Y")
Then, you can print a datetime out in the format you want with:
strToDatetime("1/3/2011").strftime("%d/%m/%Y)
>'01/03/2011'
You should never need to roll your own date/time/datetime structure in python.

Categories