İçereği Atla
Odoo Menü
  • Portal
  • Ücretsiz deneyin
  • Uygulamalar
    Finans
    • Muhasebe
    • Faturalama
    • Masraf Yönetimi
    • Elektronik Çizelge (BI)
    • Belgeler
    • İmza
    Satış
    • Müşteri İlişkileri Yönetimi (CRM)
    • Satış
    • Satış Noktası Mağaza
    • Satış Noktası Restoran
    • Abonelikler
    • Kiralama
    Web Sitesi
    • Web Sitesi Oluşturucu
    • eTicaret
    • Blog
    • Forum
    • Canlı Sohbet
    • eÖğrenme
    Tedarik Zinciri
    • Envanter
    • Üretim
    • Ürün Yaşam Döngüsü Yönetimi
    • Satın Alma
    • Bakım
    • Kalite
    İnsan Kaynakları
    • Çalışanlar
    • İşe Alım
    • İzin
    • Değerlendirme
    • Referans
    • Filo Yönetimi
    Pazarlama
    • Sosyal Medyada Pazarlama
    • E-posta ile Pazarlama
    • SMS ile Pazarlama
    • Etkinlikler
    • Pazarlama Otomasyonu
    • Anket
    Hizmetler
    • Proje Yönetimi
    • Çalışma Çizelgeleri
    • Saha Hizmeti
    • Yardım Masası
    • Planlama
    • Randevular
    Verimlilik
    • Sohbet
    • Onay
    • Nesnelerin İnterneti
    • VoIP
    • Bilgi Bankası
    • WhatsApp
    Üçüncü taraf uygulamalar Odoo Stüdyo Odoo Bulut Platformu
  • Sektörler
    Perakende satış
    • Kitapçı
    • Giyim Mağazası
    • Mobilya Mağazası
    • Gıda Marketi
    • Hırdavat Dükkanı
    • Oyuncak Dükkanı
    Gıda ve Konaklama
    • Bar ve Pub
    • Restoran
    • Fast Food Restoranı
    • Konuk Evi
    • İçecek Distribütörü
    • Otel
    Gayrimenkul
    • Emlak Acentesi
    • Mimarlık Firması
    • İnşaat
    • Emlak Yönetimi
    • Bahçe Tasarımı
    • Mülk Sahipleri Derneği
    Uzmanlık
    • Muhasebe Firması
    • Odoo Partner
    • Pazarlama Ajansı
    • Hukuk Firması
    • Yetenek Kazanımı
    • Denetim ve Belgelendirme
    Üretim
    • Tekstil
    • Metal
    • Mobilyalar
    • Gıda
    • Bira fabrikası
    • Kurumsal Hediye
    Sağlık ve Spor
    • Spor Kulübü
    • Optik Mağazası
    • Fitness Merkezi
    • Sağlıklı Yaşam Merkezi
    • Eczane
    • Kuaför Salonu
    Ticaret
    • Tamirci
    • BT Donanım & Destek
    • Güneş Enerjisi Sistemleri
    • Ayakkabı İmalatçısı
    • Temizlik Hizmetleri
    • HVAC Hizmetleri
    Diğerleri
    • Kar Amacı Gütmeyen Kuruluş
    • Çevre Ajansı
    • Reklam Panosu Kiralama
    • Fotoğrafçılık
    • Bisiklet Kiralama
    • Yazılım Bayisi
    Tüm Sektörlere Göz Atın
  • Topluluk
    Öğrenim
    • Eğitim Araçları
    • Dokümantasyon
    • Sertifikasyonlar
    • Eğitim Etkinlikleri
    • Blog
    • Podcast
    Eğitim ve Gelişim
    • Eğitim Programı
    • Scale Up! İşletme Oyunu
    • Odoo'yu Ziyaret Edin
    Yazılım
    • İndirin
    • Sürümleri Kıyaslayın
    • Sürümler
    İş Birliği
    • Github
    • Forum
    • Etkinlikler
    • Çeviriler
    • Partner Olun
    • Partnerler için Hizmetler
    • Muhasebe Firmanızı Kaydettirin
    Hizmetler
    • Partner Bulun
    • Muhasebeci Bulun
    • Bir danışmanla görüşün
    • Kurulum Hizmetleri
    • Müşteri Referansları
    • Destek
    • Sürüm Yükseltme
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Demo randevusu alın
  • Fiyatlandırma
  • Yardım

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

  • Müşteri İlişkileri Yönetimi
  • e-Commerce
  • Muhasebe
  • Envanter
  • PoS
  • Proje Yönetimi
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
Yardım

How to get users timezone for python?

Abone Ol

Get notified when there's activity on this post

Bu soru işaretlendi
moduletimezonecontext
1 Cevapla
36078 Görünümler
Avatar
Laura Jarvenpaa

I have created a module which overwrites some functions on leaves management. This function includes getting employee working schedule from contract and calculating leave length based on the contract (In my company there can be leaves that are less than one day) the times provided by working schedule are just in format: {'time_from': 8.00, 'time_to':18:00} so they don't include any kind of timezone information however dates are transformed into utc time when they are inserted to db and when you compare those times with working schedule times you need to correct timezone to user's timezone.

My code is like this and as you see there is three places where 8 is added on dates to fix this timezone problem which is fine now when our openerp is used in utc+8 but in future we plan to enable using our system outside of our LAN and then there may be people located in different timezones using it so this fix won't help in future:

def _get_number_of_days(self, date_from, date_to, cr, uid, ids, employee_id):

    DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
    date_from = datetime.datetime.strptime(date_from, DATETIME_FORMAT)
    date_to = datetime.datetime.strptime(date_to, DATETIME_FORMAT)
    timedelta = date_to - date_from
    working_shift = 86400
    diff_day = float();
    if timedelta.days > 1:
        diff_day += timedelta.days - 1

    if(employee_id):
        contract_pool = self.pool.get('hr.contract')
        active_contract_ids= contract_pool.search(cr, uid, [
        '&',
        ('employee_id', '=', employee_id),
        '|',
        '&',
        ('date_start', '<=', date_to),
        '|',
        ('date_end', '>=', date_to),
        ('date_end', '=', False),
        '&',
        '|',
        ('trial_date_start', '=', False),
        ('trial_date_start', '<=', date_to),
        '|',
        ('trial_date_end', '=', False),
        ('trial_date_end', '>=', date_to),
        ])
        if active_contract_ids:
            contract = contract_pool.browse(cr, uid, active_contract_ids[0])

            cr.execute("select hour_from, hour_to from resource_calendar_attendance where calendar_id = %s and dayofweek = %s order by hour_from;", (contract.working_hours.id, str(date_from.isoweekday())))
            start_timetable = cr.dictfetchall()
            if start_timetable:

                start_working_shift = self.pool.get('resource.calendar').working_hours_on_day(cr, uid, contract.working_hours, date_from)

                if start_working_shift:
                    # add 8 hours to fix timezone                                                                                                        
                    start_time = date_from.hour + 8 + float(date_from.minute)/60
                    if date_to.date() == date_from.date():
                        # add 8 hours to fix timezone                                                                                                    
                        end_time = date_to.hour + 8 + float(date_to.minute)/60
                        if start_time < start_timetable[0]['hour_from'] and end_time > start_timetable[len(start_timetable) - 1]['hour_to']:
                            # leave length is one day because it starts before starting hour and ends after ending hour                                  
                            return 1           
                        else:
                            hours = self._calculate_hours_for_working_day(start_timetable, start_time, end_time)
                            return hours / start_working_shift
                    if start_time < start_timetable[0]['hour_from']:
                            # leave length is one day because it starts before starting hour and ends after ending hour                               
                            diff_day += 1
                    else:
                        end_time = float(start_timetable[len(start_timetable) - 1]['hour_to'])
                        hours = self._calculate_hours_for_working_day(start_timetable, start_time, end_time)
                        diff_day += hours / start_working_shift


            cr.execute("select hour_from, hour_to from resource_calendar_attendance where calendar_id = %s and dayofweek = %s order by hour_from;", (contract.working_hours.id, str(date_to.isoweekday())))
            end_timetable = cr.dictfetchall()
            if end_timetable:
                end_working_shift = self.pool.get('resource.calendar').working_hours_on_day(cr, uid, contract.working_hours, date_to)
                if end_working_shift:
                    start_time = float(end_timetable[0]['hour_from'])
                    # add 8 hours to fix timezone                                                                                                        
                    end_time = date_to.hour + 8 + float(date_to.minute)/60
                    if end_time > start_timetable[len(start_timetable) - 1]['hour_to']:
                        # leave length is one day because it starts before starting hour and ends after ending hour                                      
                        diff_day += 1
                    else:
                        hours = self._calculate_hours_for_working_day(end_timetable, start_time, end_time)
                        diff_day += hours / end_working_shift

        else:
            # tell user that employee don't have contract so leaves can't be  calculated                                                                 
            raise osv.except_osv(_('Error'), _('Employee doesn\'t have contract. Leave request can\'t be done.'))
    else:
        diff_day = timedelta.days + float(timedelta.seconds) / working_shift
    return diff_day

Tried to fix this by adding parameter context for onchange function of the date selection and using pytz to transform these times to right timezone:

active_tz = pytz.timezone(context.get("tz","UTC")

this did not work (found this solution from another module but well as their module didn't work properly either it's not too big surprise that this did not work).

0
Avatar
Vazgeç
Avatar
Jeroen Mollers
En İyi Yanıt

To get the user's timezone you could do something like this in your code:

Version 7.0 code:

import pytz
from openerp import SUPERUSER_ID

# get user's timezone
user_pool = self.pool.get('res.users')
user = user_pool.browse(cr, SUPERUSER_ID, uid)
tz = pytz.timezone(user.partner_id.tz) or pytz.utc

# get localized dates
date_from = pytz.utc.localize(datetime.datetime.strptime(date_from, DATETIME_FORMAT)).astimezone(tz)
date_to   = pytz.utc.localize(datetime.datetime.strptime(date_to, DATETIME_FORMAT)).astimezone(tz)

Users that use version 6.1 should change the code line:

tz = pytz.timezone(user.partner_id.tz) or pytz.utc

into code line:

tz = pytz.timezone(user.context_tz) or pytz.utc
4
Avatar
Vazgeç
Laura Jarvenpaa
Üretici

Thanks this was helpful but at least in version 7 I had to do following modification on your code: user_pool = self.pool.get('res.partner') user = user_pool.browse(cr, SUPERUSER_ID, uid) tz = pytz.timezone(user.tz) or pytz.utc because timezone info is now in res.partner not in res.users and timezone info provided by that table had to be converted into timezone as it is only string. If you add these modifications to your answer I can mark it as right.

Jeroen Mollers

You are correct. My code was for version 6.1. In your suggested modification you retrieve a partner record based on a user's ID. I suggest to modify my original code from "tz = pytz.timezone(user.context_tz) or pytz.utc" to "tz = pytz.timezone(user.partner_id.tz) or pytz.utc". I have modified my original answer and also included the version 6.1 one in case someone is interested in that one.

Laura Jarvenpaa
Üretici

Ok, good to know.

Ashish Singh

when we print "date_from" its display like '2014-08-14 05:25:55+05:30' i am using time-zone 'Asia/Kolkata'

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

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

Üye Ol
İlgili Gönderiler Cevaplar Görünümler Aktivite
time zone is missing in context when a scheduler method is invoked
timezone scheduler context
Avatar
0
Eki 16
4414
context not work ???
context
Avatar
Avatar
1
Oca 25
2071
Error when importing module Product Bidding In ECommerce in odoo 17
module
Avatar
Avatar
1
Tem 24
2604
Missing required value for the field 'Model' (model_id)
module
Avatar
Avatar
1
Oca 24
6485
Time zone problem in python
timezone
Avatar
Avatar
2
Nis 23
4094
Topluluk
  • Eğitim Araçları
  • Dokümantasyon
  • Forum
Açık Kaynak
  • İndirin
  • Github
  • Runbot
  • Çeviriler
Hizmetler
  • Odoo.sh Hosting
  • Destek
  • Sürüm Yükseltme
  • Özel Geliştirmeler
  • Eğitim
  • Muhasebeci Bulun
  • Partner Bulun
  • Partner Olun
Hakkında
  • Şirketimiz
  • Pazarlama Gereçleri
  • İletişim
  • Kariyer
  • Etkinlikler
  • Podcast
  • Blog
  • Müşteriler
  • Hukuki • Gizlilik
  • Güvenlik
الْعَرَبيّة 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, müşteri ilişkileri yönetimi, eTicaret, muhasebe, envanter, satış noktası, proje yönetimi gibi şirketinizin tüm ihtiyaçlarını karşılayan bir açık kaynak işletme uygulamaları paketidir.

Odoo’nun eşsiz değer önermesi, aynı anda hem kullanımının çok kolay olup hem de tamamen entegre olmasıdır.

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