Skip to Content
Odoo Menu
  • Prihlásiť sa
  • Vyskúšajte zadarmo
  • Aplikácie
    Financie
    • Účtovníctvo
    • Fakturácia
    • Výdavky
    • Tabuľka (BI)
    • Dokumenty
    • Podpis
    Predaj
    • CRM
    • Predaj
    • POS Shop
    • POS Restaurant
    • Manažment odberu
    • Požičovňa
    Webstránky
    • Tvorca webstránok
    • eShop
    • Blog
    • Fórum
    • Živý chat
    • eLearning
    Supply Chain
    • Sklad
    • Výroba
    • Správa životného cyklu produktu
    • Nákup
    • Údržba
    • Manažment kvality
    Ľudské zdroje
    • Zamestnanci
    • Nábor zamestnancov
    • Voľné dni
    • Hodnotenia
    • Odporúčania
    • Vozový park
    Marketing
    • Marketing sociálnych sietí
    • Email marketing
    • SMS marketing
    • Eventy
    • Marketingová automatizácia
    • Prieskumy
    Služby
    • Projektové riadenie
    • Pracovné výkazy
    • Práca v teréne
    • Helpdesk
    • Plánovanie
    • Schôdzky
    Produktivita
    • Tímová komunikácia
    • Schvalovania
    • IoT
    • VoIP
    • Znalosti
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Priemyselné odvetvia
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Reštaurácia
    • Fast Food
    • Guest House
    • Beverage distributor
    • Hotel
    Reality
    • Real Estate Agency
    • Architecture Firm
    • Konštrukcia
    • Estate Managament
    • Gardening
    • Property Owner Association
    Poradenstvo
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Výroba
    • Textile
    • Metal
    • Furnitures
    • Jedlo
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware and Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Iní
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Komunita
    Vzdelávanie
    • Tutoriály
    • Dokumentácia
    • Certifikácie
    • Školenie
    • Blog
    • Podcast
    Empower Education
    • Vzdelávací program
    • Scale Up! Business Game
    • Visit Odoo
    Softvér
    • Stiahnuť
    • Porovnanie Community a Enterprise vierzie
    • Releases
    Spolupráca
    • Github
    • Fórum
    • Eventy
    • Preklady
    • Staň sa partnerom
    • Services for Partners
    • Register your Accounting Firm
    Služby
    • Nájdite partnera
    • Nájdite účtovníka
    • Meet an advisor
    • Implementation Services
    • Zákaznícke referencie
    • Podpora
    • Upgrades
    ​Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Získajte demo
  • Cenník
  • Pomoc

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

  • CRM
  • e-Commerce
  • Účtovníctvo
  • Sklady
  • PoS
  • Projektové riadenie
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tagy (View all)
odoo accounting v14 pos v15
About this forum
Pomoc

how to calculate difference bitween two dates ?

Odoberať

Get notified when there's activity on this post

This question has been flagged
17 Replies
54192 Zobrazenia
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
Zrušiť
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
Zrušiť
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
Zrušiť
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
Zrušiť
Enjoying the discussion? Don't just read, join in!

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

Registrácia
Komunita
  • Tutoriály
  • Dokumentácia
  • Fórum
Open Source
  • Stiahnuť
  • Github
  • Runbot
  • Preklady
Služby
  • Odoo.sh hosting
  • Podpora
  • Vyššia verzia
  • Custom Developments
  • Vzdelávanie
  • Nájdite účtovníka
  • Nájdite partnera
  • Staň sa partnerom
O nás
  • Naša spoločnosť
  • Majetok značky
  • Kontaktujte nás
  • Pracovné ponuky
  • Eventy
  • Podcast
  • Blog
  • Zákazníci
  • Právne dokumenty • Súkromie
  • Bezpečnosť
الْعَرَبيّة 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 je sada podnikových aplikácií s otvoreným zdrojovým kódom, ktoré pokrývajú všetky potreby vašej spoločnosti: CRM, e-shop, účtovníctvo, skladové hospodárstvo, miesto predaja, projektový manažment atď.

Odoo prináša vysokú pridanú hodnotu v jednoduchom použití a súčasne plne integrovanými biznis aplikáciami.

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