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

odoo 16: how to add time in Datetime and days/week/month(s) in Date field for default value

Suscribirse

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

Se marcó esta pregunta
datedatetimeodoo16features
1 Responder
10445 Vistas
Avatar
SmithJohn45

i have created a model with a Date and a Datetime field, want to know to set default values:

1) how i can add Day(s) / Week(s) / Month(s) in Date and Datetime field in model to assign a default value?

2) how to add time in Datetime field in model to assign a default value?

right now, i have following default values and if i want by default add 3 days in today's Date how i can ( same for week and month ) and what if i want to add 30min or 1 hour in time ( Datetime field )  

appointment_time = fields.Datetime (string='Appointment Time', default=fields.Datetime.now)
booking_date = fields.Date(string='Booking Date', default=fields.Date.context_today)


please help.

regards

0
Avatar
Descartar
Avatar
Niyas Raphy (Walnut Software Solutions)
Mejor respuesta

Hi,

If you search inside the odoo source code for the usage of relativedelta you will get a lot of such samples.

lead_days_date = fields.Date.today() + relativedelta.relativedelta(days=10)

The above code will add 10 days to today's date, similar you can change month and year.


For more: https://dateutil.readthedocs.io/en/stable/relativedelta.html

Thanks

1
Avatar
Descartar
SmithJohn45
Autor

thank you @Niyas Raphy , will check the link to learn further. regards

SmithJohn45
Autor

@Niyas Raphy, i just tried your code as below but when upgrading my app/module, it is saying that booking_date field is not in database ( i have used in patient_view.xml ).

booking_date = fields.Date.today() + relativedelta(days=3)

how i can have the field with data or this code is used in a compute function? or something else? i searched odoo default addons folder for relativedelta yet failed to find how to set default value as mentioned in my opening post above. or i am missing something or this is my wrong approach etc.?

please help.
regards

SmithJohn45
Autor

when using relativedelta.relativedelta(days=3) it is not starting server and showing error

type object 'relativedelta' has no attribute 'relativedelta'

may be i have to import something for this purpose.
regards

SmithJohn45
Autor

for field booking_date which type is Date is working fine now with code below:

booking_date = fields.Date(default=str(datetime.now() + relativedelta.relativedelta(days=3)))

but for Datetime type field it is thowing error when going to create New record. error as below (the last line only because there are several lines):

ValueError: unconverted data remains: .191905

may be i have to use some other pythong function to convert it correctly for Datetime field, please help.
regards

SmithJohn45
Autor

@Niyas Raphy thank you for helping us.

its done now, also modified Datetime type field to have default date + time as below:

appointment_time = fields.Datetime(default=datetime.today() + relativedelta.relativedelta(days=3, hours=3))

please advise if i am doing wrong or missing something.
regards

¿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
Need Studio compute code to show number of days from today vs. a date field Resuelto
date datetime
Avatar
Avatar
2
ene 24
3597
Adding days to a date
date datetime
Avatar
Avatar
Avatar
2
jun 22
5683
How can I use date format only without time? Resuelto
date datetime
Avatar
Avatar
2
jun 18
7029
[SOLVED] How can I hide the time of Datetime field of a quotation (doc.date_order)? Resuelto
date datetime
Avatar
Avatar
Avatar
2
nov 16
15074
how to find number of days between two dates? Resuelto
date datetime
Avatar
Avatar
Avatar
2
feb 24
13572
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