Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

How to exclude specific day between two date in calculation ?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
pythondateexcludeignore
13 Respuestas
14555 Vistas
Avatar
Ankit H Gandhi(AHG)

Hello People,

I want to total number of days from two dates. but there is one condition to count total number of day but excluded(ignore) specific day ?

Like

I have below dates  

start date: 01/01/2015

end date: 31/03/2015

Here I want total number of days between start date and end date, but not including " Tuesday " in total number of days.

Thanks in Advance.

1
Avatar
Descartar
Avatar
Temur
Mejor respuesta

@Ankit, here is brute-force version:

from datetime import datetime, date, timedelta

date_start = datetime.strptime('2015-01-01','%Y-%m-%d').date()
date_end = datetime.strptime('2015-03-31','%Y-%m-%d').date()

delta_day = timedelta(days=1)

days = {'mon':0,'tue':1,'wed':2,'thu':3,'fri':4,'sat':5,'sun':6}

dt = date_start
day_count=0

while dt <= date_end:
if dt.weekday() != days['tue']:
day_count+=1
dt += delta_day

But suggestion of @Drees is much more lightweight and should be executed faster for large periods, if you'll get it worked.


UPDATE:

slightly modified approach suggested by @Drees, if we make sure day count starts at the weekday we are interested in (by "removing" days before first occurrence of the target day i.e. weekday to be excluded), then total count of weekday occurrence will be:

# total_days  -- days between start_date (inclusive) and and_date (inclusive)
# days_before -- days from total_days period, that are before first occurrence of the weekday to be excluded

weekday_count = (total_days - days_before) / 7

if (total_days - days_before) % 7:
weekday_count = weekday_count + 1

days_wit_excluded_target_day = total_days - weekday_count

If we're agree that above code may calculate correctly the day count in [start_date, end_date] period with a target_weekday excluded, then there is a corresponding code:

version with calculation

from datetime import datetime

date_start_val = '2015-01-01' # start date (inclusive)
date_end_val = '2015-03-31' # end date (inclusive)

date_start = datetime.strptime(date_start_val,'%Y-%m-%d').date()
date_end = datetime.strptime(date_end_val,'%Y-%m-%d').date()

days = {'mon':0,'tue':1,'wed':2,'thu':3,'fri':4,'sat':5,'sun':6}

total_days = (date_end - date_start).days + 1

first_weekday = date_start.weekday()
target_weekday = days['tue']

if target_weekday == first_weekday:
days_before = 0
elif target_weekday < first_weekday:
days_before = 7 - first_weekday + target_weekday
else:
days_before = target_weekday - first_weekday
 
weekday_count = total_days - days_before
if weekday_count > 0:
weekday_count = weekday_count/7 + (weekday_count%7 and 1 or 0)
else:
weekday_count = 0

day_count = total_days - weekday_count

this version should be much faster on large periods then other versions.


1
Avatar
Descartar
Ankit H Gandhi(AHG)
Autor

Thanks for your help @ Temur !!! It is fully working...+1

Temur

Please see the last version that I've added after update. it's a recommended version.

Temur

wrapped code into the python function, see a gist

Ankit H Gandhi(AHG)
Autor

Sorry @ Temur Using updated code I am not get perfect total days. I am using below date for count date_start_val = '2015-07-04' date_end_val = '2015-07-05' I got total number of days in 0 (zero), but actually total number of days will be 2 (Two) . Please advice on it.

Temur

<=0 as there is not Tuesday at all in date range ['2015-07-04','2015-07-05' ] then day_count = 0 were executed under else clause in the above code fragment, instead of weekday_count = 0. It's corrected now in the answer and function in gist is updated accordingly.

Ankit H Gandhi(AHG)
Autor

Thanks again now it's work fine..@ Temur

Temur

You're welcome

Avatar
Rihene
Mejor respuesta

Hi Ankit;

What i propose to you is to calculate the total of days between start_date and end_date.

And then, to get your 'Tuesday' day you have to divide the total number by seven.

And you have to get the day of the first_date as shown by this code:

Python:

>>> import datetime

>>> datetime.datetime.today()

datetime.datetime(2012, 3, 23, 23, 24, 55, 173504)

>>> datetime.datetime.today().weekday()

4

Where weekday Returns the day of the week as an integer, where Monday is 0 and Sunday is 6.

Example:

Total_date = 29

29/7 = 4 + 1 so there is 4 tuesday and 1 < 3 if the start_date is monday

so total_date becomes 25.

Hope this may help you :)

Regards.

2
Avatar
Descartar
Ankit H Gandhi(AHG)
Autor

Thanks for you quick response @ Dress Far +1 I had little bit confusion with your code but @ Temur solved out confusion

Avatar
Akhil P Sivan
Mejor respuesta

Hi Ankit,

If the start date and end date are fields of type date, you can try the following code:

For example, to avoid tuesdays and get the day count:

import dateutil.parser
import datetime
from openerp import models, fields

class your_class(models.Model):
_name = "your.model"

def your_function(self):
days_count = 0
while (start_date < end_date):
day = dateutil.parser.parse(start_date).date().weekday()
if day != 1:
days_count += 1
start_date = start_date + datetime.timedelta(days=1)

Here days_count will give the no. of days between two dates avoided tuesday

if the start_date and end_date are not date fields, you need convert to date type like this:

s_date = dateutil.parser.parse(start_date).date()
1
Avatar
Descartar
Ankit H Gandhi(AHG)
Autor

Thanks @ Akhil.. It is work fine. +1

Avatar
Rabie Sakhri
Mejor respuesta

Thanks for this help

0
Avatar
Descartar
¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
How to verify that a field date is empty? Resuelto
python date
Avatar
Avatar
Avatar
3
dic 23
46655
Format language date_format '%B' in python Resuelto
language python date
Avatar
Avatar
1
mar 17
29634
transformation of date
python date change
Avatar
Avatar
Avatar
2
mar 16
4422
How to extract the month from a date field?
python date month odoo9
Avatar
Avatar
Avatar
2
may 22
17573
How can i get sum of records between two dates? Resuelto
python date datetime odoo
Avatar
Avatar
3
mar 24
5314
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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