Search code examples
pythontimezonereportodoo

how to change odoo server timezone to user timezone in attendance report


i have been customized an odoo report to print employee attendances the time of check in and out is correct in UI but when i print the report it increase 2 hours to every record


Solution

  • It is a timezone problem: dates in Odoo are written as UTC datetime objects. When a date is rendered in the browser UI, it is automatically converted to the user's device timezone, but this conversion is not automatic when it comes to report, where datetime fields are rendered exactly as they are saved in the database.

    Try to create a method that parses the datetime objects according to the user configuration:

    import logging
    import pytz
    _logger = logging.getLogger(__name__)
    
    def convert_datetime_field(datetime_field, user=None):
        dt = datetime.strptime(datetime_field, '%Y-%m-%d %H:%M:%S')
        if user and user.tz:
            user_tz = user.tz
            if user_tz in pytz.all_timezones:
                old_tz = pytz.timezone('UTC')
                new_tz = pytz.timezone(user_tz)
                dt = old_tz.localize(dt).astimezone(new_tz)
            else:
                _logger.info("Unknown timezone {}".format(user_tz))
    
        return datetime.strftime(dt, '%d/%m/%Y %H:%M:%S')