Passa al contenuto
Menu
È necessario essere registrati per interagire con la community.
La domanda è stata contrassegnata
2 Risposte
4216 Visualizzazioni

I have a schedule model with start date, start hour and start minute, and I need to compute the start datetime from these above fields. Since Odoo server is force in UTC AFAIK, it's impossible for me to compute the datetime right without having a timezone reference. Is there any way to do that without storing timezone?

Avatar
Abbandona
Risposta migliore

Hi,

Yes, it is not possible to accurately compute the start datetime from the start date, start hour, and start minute fields without storing a timezone reference.

As you mentioned, Odoo server is forced to use UTC, which means that any date or time values stored without a timezone will be assumed to be in UTC. This can lead to incorrect calculations when converting to or from local timezones.

You can make use of the pytz library in Python. This library provides a timezone database that can be used to localize a datetime object to a specific timezone.

Eg:

import pytz
from datetime import datetime, time

# assume start_hour and start_minute are integers representing the start time
start_hour = 10
start_minute = 30
# define a timezone, in this case assuming the user's local timezone
local_tz = pytz.timezone('Europe/London')

# create a time object from the hour and minute values
start_time = time(hour=start_hour, minute=start_minute)

# get the current date in the user's timezone
today = datetime.now(local_tz).date()

# combine the date and time to create a datetime object
start_datetime = local_tz.localize(datetime.combine(today, start_time))

# convert the datetime object to UTC for storage in the database
start_datetime_utc = start_datetime.astimezone(pytz.utc)


By using pytz to localize the datetime to a specific timezone, we can compute the correct UTC value without needing to store an additional timezone reference in the database.


Thanks


Avatar
Abbandona
Risposta migliore

Hello Tung Nguyen,

First you need to convert start hour and start minute into time format, for this you can use

start_time = time(hours, minutes)

Here, specify start hour in place of 'hours' and start minute in 'minutes'.

Second, you need to combine this start_time with your start date, for this you can refer this below code

start_datetime = datetime.combine(start_date, start_time)
your_datetime_field_name = start_datetime

This will compute the start datetime.

Hope this is helpful.

Avatar
Abbandona
Post correlati Risposte Visualizzazioni Attività
3
lug 25
4803
6
set 19
12107
2
mar 16
8422
0
mar 15
8799
1
gen 24
13206