Search code examples
pythonodoo-11

How to export date time as per my timezone in odoo 11?


I tried to export datetime field of Attendance but i am getting wrong date time value. It is giving UTC date time instead my my timezone datetime.

How can i resolve this issue? Please help me.


Solution

  • I just update in main.py file of controller of Web module. You can do this in inherit the main.py file.

    Import below package in main.py

    from dateutil.parser import parse
    import datetime
    import pytz
    

    -->Update in CSVExport class for CSV. Add below code in this class.

    def check_date(self, value):
    try:
        parse_data = parse(value)
        return parse_data
    except Exception as e:
        return False
    

    Update from_data() function like below code.

    def from_data(self, fields, rows):
       fp = io.BytesIO()
       writer = pycompat.csv_writer(fp, quoting=1)
       writer.writerow(fields)
       for data in rows:
         row = []
         for d in data:
            if isinstance(d, pycompat.string_types) and d.startswith(('=', '-', '+')):
                d = "'" + d
            if type(d) is str:
                parse_data = self.check_date(d)
                if parse_data:
                    if len(d) > 10:
                        tz = pytz.timezone(request._context.get('tz'))
                        d = (pytz.utc.localize(datetime.datetime.strptime(d,'%Y-%m-%d %H:%M:%S')).astimezone(tz)).strftime('%Y-%m-%d %H:%M:%S')
    
            row.append(pycompat.to_text(d))
         writer.writerow(row)
      return fp.getvalue()
    

    -->For Excel Update below code in ExcelExportV class in datetime condition.

    elif isinstance(cell_value, datetime.datetime):
      tz = pytz.timezone(request._context.get('tz'))
      cell_value = (pytz.utc.localize(cell_value).astimezone(tz)).strftime('%Y-%m-%d %H:%M:%S')
      cell_style = datetime_style
    

    After that, restart your odoo service and check.