Skip to Content
Menu
This question has been flagged
2 Replies
1916 Views

I'm trying to extract the date from a datetime field using date(), but anything prior to 11am returns the previous day. I believe this is because I am operating in a UTC+11 timezone.


I have created a simple model for testing, with the following 3 fields:

x_studio_timestamp (datetime)

x_studio_date_time (datetime)

x_studio_date_only (date)


I have created an automated action on create and update which is triggered on x_studio_timestamp.


The Python code is ...


record['x_studio_date_time'] = record.x_studio_timestamp

record['x_studio_date_only'] =record.x_studio_timestamp.date()


When I create or update a record, the field x_studio_date_time correctly matches x_studio_timestamp. However x_studio_date_only will display the date of the previous day whenever the time portion of x_studio_timestamp is prior to 11am

 

Avatar
Discard
Best Answer

Hi,

Refer to the code
Built-in pytz library to handle time zones. Here's a step-by-step guide on how to extract the local date and time from a Datetime field in Odoo 16:

from odoo import models, fields
from pytz import timezone
from datetime import datetime
class ResPartnerExtended(models.Model):
_inherit = 'res.partner'

local_datetime = fields.Datetime(string='Local Date and Time', compute='_compute_local_datetime')

def _compute_local_datetime(self):
for record in self:
if record.date_field:
# Replace 'date_field' with the name of your Datetime field
user_tz = self.env.user.tz or 'UTC' # Get the user's timezone
server_tz = self.env['ir.config_parameter'].sudo().get_param('odoo_server_timezone') # Get the server's timezone
partner_tz = record.partner_timezone or 'UTC' # Get the partner's timezone (if applicable)

local_datetime = record.date_field

# Convert to user's timezone
user_timezone = timezone(user_tz)
local_datetime = user_timezone.localize(local_datetime).astimezone(timezone(server_tz))

# Convert to partner's timezone (if applicable)
if partner_tz != server_tz:
partner_timezone = timezone(partner_tz)
local_datetime = local_datetime.astimezone(partner_timezone)

record.local_datetime = local_datetime
else:
record.local_datetime = False


Hope it helps

Avatar
Discard
Author Best Answer

I solved this as follows:

user_tz = env.user.tz


record['x_studio_date_time'] = record.x_studio_timestamp

record['x_studio_date_only'] = timezone(user_tz).fromutc(record.x_studio_timestamp).date()


Avatar
Discard