This question has been flagged
3 Replies
19381 Views

Hello,

I have a model with a date field to be an user input, and a computed datetime field. Something like this:

class MyModel(models.Model):
_name = "my.model"

my_date = fields.Datetime(string='My date')
my_datetime = fields.Datetime(string='My datetime', compute='_get_datetime_from_date')

My problem is that the computed datetime is stored according my timezone, for example if I'm on UTC-3 and I enter 01/01/2018 in my_date, my_datetime is computed as 31/12/2017 21:00:00. This is a problem for any datetime behind UTC as it's effectively stored as the day before. I need it to be stored as 01/01/2018 0:00:00. How can I solve this issue?

Thanks a lot.

Avatar
Discard

Can you post the code of _get_datetime_from_date?

Can you post your compute method code ??

Best Answer

Hi Hugo,

I was having this same issue, so solved like passing Timezone and converting into UTC to save in database, like following:

def convert_TZ_UTC(self, TZ_datetime):
fmt = "%Y-%m-%d %H:%M:%S"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
# Convert to current user time zone
now_timezone = now_utc.astimezone(timezone(self.env.user.tz))
UTC_OFFSET_TIMEDELTA = datetime.strptime(now_utc.strftime(fmt), fmt) - datetime.strptime(now_timezone.strftime(fmt), fmt)
local_datetime = datetime.strptime(TZ_datetime, fmt)
result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
return result_utc_datetime.strftime(fmt)
Avatar
Discard
Author

Thanks! It worked perfectly.

Glad to know :)

Hi

where is 'TZ_datetime' using

TZ_datetime is variable of datetime type that would be converted to UTC format

Can you please help, how to use this function in my custom module field datetime. i want to show datetime in utc to all users.