Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita 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
  • Proyectos
  • 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

Datetime in python

Suscribirse

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

Se marcó esta pregunta
python2.7
7 Respuestas
25372 Vistas
Avatar
Demirel yakito

i want to find the time difference between two time in python. this is my code i got a type error. is this FMT is correct for this datetime?

import time

from datetime import datetime
s1=datetime.now()
print s1
time.sleep(2)
s2=datetime.now()
print s2

FMT = '%Y-%m-%d %H:%M:%s'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
print tdelta

 

 

output is:

2014-12-31 17:33:59.692952
2014-12-31 17:34:01.695124
Traceback (most recent call last):
  File "/opt/odoo/trial_projects/check.py", line 14, in <module>
    tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
TypeError: must be string, not datetime.datetime

 

0
Avatar
Descartar
Avatar
Qutechs, Ahmed M.Elmubarak
Mejor respuesta

Hello,

when you're trying this:

tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

the s2 and s1 are datetime.datetime objects so you got the error.
you have to change the FMT to :

FMT = '%Y-%m-%d %H:%M:%S.%f'

because .now() return time with msconds ...

then use

tdelta = datetime.strptime(str(d2),FMT) - datetime.strptime(str(d1),FMT)

then you'll get datetime.timedelta object ....

I hope this will help you ...

 

3
Avatar
Descartar
Avatar
Kirubanidhi Rajarathinam
Mejor respuesta

Hai demirel,

     Please specify a header file,

                    from datetime import datetime

     First create a two datetime field in py file,

ex:

                    start_work = fields.Datetime(string="Start work")

                    end_work = fields.Datetime(string="End work")

                    work_hours=fields.Float(string="Total Working Hours",compute='sal_cal',store=True)

then create a compute function name as sal_cal

                    @api.depends('start_work','end_work')

                    def sal_cal(self):

                        t1= datetime.strptime(self.start_work, '%Y-%m-%d %H:%M:%S')

                        t2= datetime.strptime(self.end_work, '%Y-%m-%d %H:%M:%S')

                        s= datetime.strptime(str(t2.time()),'%H:%M:%S') - datetime.strptime(str(t1.time()),'%H:%M:%S')

In this above code is working perfectly to me.please check it now and let me know if any issue are occured


2
Avatar
Descartar
Kirubanidhi Rajarathinam

In this above code output is:

2016-06-09 02:30:16

02:30:16

2016-06-09 09:48:43

09:48:43

7:18:27

Avatar
Anand
Mejor respuesta

use this for ref.... surely it will heelp you..

from datetime import datetime
d1='2014-11-15'
d2='2013-11-15'
d1 = datetime.strptime(d1, "%Y-%m-%d")
d2 = datetime.strptime(d2, "%Y-%m-%d")
print abs((d2 - d1).days)/(12*30)
print datetime.now().date()

1
Avatar
Descartar
Gopalakrishnan Kasilingam

Hi Anand your code show's date alone not the time.

Anand

just add like abs((d2 - d1).days)*24

Avatar
Demirel yakito
Autor Mejor respuesta

i want to find day with time difference...


 

0
Avatar
Descartar
Anand

just add like abs((d2 - d1).days)*24

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

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

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Error occurred during the installation of loan management(V6.1) module in V7.0
python2.7
Avatar
Avatar
Avatar
Avatar
3
oct 23
6746
How to write a python function called automatically?
python2.7
Avatar
Avatar
Avatar
2
ene 23
6153
AttributeError: 'module' object has no attribute 'model'
python2.7
Avatar
Avatar
Avatar
Avatar
Avatar
11
sept 19
39350
Urllib2.py missing ? or where is it ?
python2.7
Avatar
0
may 16
4660
Python Library ? where are there ?
python2.7
Avatar
0
abr 16
4856
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • 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 estar 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