如何在Odoo XML报表中获取并显示前一日日期
To modify your existing code to display the previous day instead of the current date, you'll need to subtract one day from the current datetime value before formatting it. Here's how to do it properly:
Quick Adjustment to Your Original Code
Your current code uses datetime.datetime.now() to get the server's local time. To get the prior day, simply subtract a timedelta of 1 day:
context_timestamp(datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%d-%m-%Y')
Best Practice: Use UTC Time (Recommended)
Odoo's fields.Datetime.now() returns the current UTC datetime, which is more reliable for timezone-aware applications. Combine this with subtracting a day and converting to the user's timezone via context_timestamp:
context_timestamp(fields.Datetime.now() - datetime.timedelta(days=1)).strftime('%d-%m-%Y')
Key Notes:
- Ensure the
datetimemodule is available in your report context (it's included by default in most Odoo QWeb templates). context_timestamphandles converting the UTC datetime to the user's configured timezone, so the previous day will be correctly adjusted based on their local time.- The
strftime('%d-%m-%Y')part keeps your desired date format (day-month-year).
If you're working in a Python controller or model instead of a QWeb template, the logic remains the same—just make sure to import the necessary modules where necessary:
from datetime import datetime, timedelta from odoo import fields # Example in a model method def get_previous_day(self): utc_yesterday = fields.Datetime.now() - timedelta(days=1) return self.env.context_timestamp(utc_yesterday).strftime('%d-%m-%Y')
内容的提问来源于stack exchange,提问作者anand natesh

