Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

how to calculate difference bitween two dates ?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
17 Respostes
54189 Vistes
Avatar
jean44

Hi, in my object I have two date fields: date1:fields.date('date 1'), date2:fields.date('date 2'),

I want to retrieve the difference of that 2 fields I tried this : date2 - date1 but I got this error : TypeError: unsupported operand type(s) for -: 'str' and 'str'

3
Avatar
Descartar
OpenERP Vietnam

to do this, the first you must convert into date format (use lib datetime: datetime.date(year, month, day)). Then you can use operator '-' in this case. Refer: http://docs.python.org/2/library/datetime.html

jean44
Autor

thank you !

Avatar
nishad
Best Answer

Hi mos, You need to do some python level stuffs with dates for getting exact date difference , i will explain with an example

from datetime import datetime

fmt = '%Y-%m-%d'
from_date = '2013-09-01'     -> Take your date field1
to_date = '2013-09-31'       -> Take your date field2

d1 = datetime.strptime(from_date, fmt)

d2 = datetime.strptime(to_date, fmt)

daysDiff = str((d2-d1).days)          -> will gives you 29 days

daysDiff = str((d2-d1).days + 1)      -> will gives you 30 days

Hope it helps you ........ Thanks

8
Avatar
Descartar
jean44
Autor

thank you !

Atul Kumar jain

hi nishad thanks for your answer i want to calculate it automatically and show in readonly=True field so can you please provide me some extra detail for calculate duration

nishad

Define two date fields(from date , to date) & one functional field(difference_days) to keep the difference days. Do implement the date difference calculation steps in your function and return the value . A functional field in openerp will return a readonly = True value by default. If you want to save data in to DB then use store=True parameter while defining functional field.

Atul Kumar jain

my field is 'date_s':fields.datetime('Start Date'), 'date_e':fields.datetime('End Date'), 'duration':fields.function(_get_days, string='Duration', store=True), and my function is this def _get_days(self, cr, uid, ids, field_name, args, context=None): res = {} for date in self.browse(cr, uid, ids, context=context): res[date.id] = ((date.date_s-date.date_e).days) or False return res but it give me error like this res[date.id] = ((date.date_s-date.date_e).days) or False TypeError: unsupport

nishad

You need to include 'from datetime import datetime' in the import section and then do a date formatting using 'datetime.strptime(from_date, fmt)' for each date fields where fmt = '%Y-%m-%d' , because we are doing a conversion from openerp datetime format to native python format and then calculating the difference . Do one by one as i shown in my source code instead of doing it in single step.

Atul Kumar jain

i correct my function but still i got error like this data_string[found.end():]) ValueError: unconverted data remains: 10:52:57 and my function is def _get_days(self, cr, uid, ids, field_name, args, context=None): res = {} for date in self.browse(cr, uid, ids, context=context): fmt = '%Y-%m-%d' date.date_s = datetime.strptime(date.date_s, fmt) date.date_e = datetime.strptime(date.date_e, fmt) res[date.id] = ((date.date_s-date.date_e).days) or False return res

nishad

This is because your fields are of type' datetime' , instead use normal 'date' in openerp.

Atul Kumar jain

i already do that but still got erro

Atul Kumar jain

hi nishad please help me

nishad

def _get_days(self,cr,uid,ids,field_name, arg ,context=None):
res = {}, fmt = '%Y-%m-%d', for object in self.browse(cr, uid, ids, context=context): res[object.id] = {'diff_days':0, } from_date = object.date_a, to_date = object.date_b, d1 = datetime.strptime(from_date, fmt), d2 = datetime.strptime(to_date, fmt) ,daysDiff = str((d2-d1).days), res[object.id]['diff_days'] = daysDiff , return res

nishad

'date_a':fields.date("Date1"), 'date_b':fields.date("Date2"), 'diff_days':fields.function(_get_days,string="Diff days", multi='sums',store=True),

Atul Kumar jain

Hi nishad thanks for your reply i solve this problem

Tochukwu Eze

Hi
I am got this error (TypeError: unsupported operand type(s) for -: 'str' and 'str')when I tried out the above code.
Please can anyone help me out.
Thanks

Avatar
Silverstar
Best Answer

Hi,

This coluld be helpful.


date = fields.Date.from_string(old_date)

 worked_days = (fields.date.today() - date).days


Regards,

1
Avatar
Descartar
Tochukwu Eze

Hi Atul Kumar jain
Please how did you solve the above because I am having the same issue

Silverstar
Hi,

What is the issue are you facing?

On Fri, 24 Sep 2021, 5:31 pm Tochukwu Eze, <tochukwu.eze@primespectrum.com> wrote:

Hi Atul Kumar jain
Please how did you solve the above because I am having the same issue

Sent by Odoo S.A. using Odoo.

Avatar
zahid
Best Answer

Use timedelta object form python

from datetime import timedelta

https://docs.python.org/2/library/datetime.html#timedelta-objects

0
Avatar
Descartar
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now