简体   繁体   中英

How to force time in datetime field when saving a record in odoo?

In my odoo module, I have a datetime field (prefered_date). What I want to do is that, no matter what time the user enters, the time is always set at 10 am. I tried to do it with the following code. but is not working. The time is getting set to 6 am instead of 10 . Maybe it has something to do with the timezone. What am I doing wrong?

@api.multi
def write(self, values):
    if 'prefered_date' in values:
        date = datetime.strptime(values.get('prefered_date'), '%Y-%m-%d %H:%M:%S')
        newdate = date.replace(hour=10, minute=0)
        new = newdate.strftime("%Y-%m-%d %H:%M:%S")
        values['prefered_date'] = new 
    return super(PostabilidadRequest, self).write(values)

One thing I'm missing in your question is where you're seeing this 6 am value: do you see this in the browser, or in python?

I'm guessing you're seeing this value in the browser. Any date objects in the database are stored as UTC and the front-end will use the user's timezone to show the right (local) time. Could it be you are in a time zone that is in UTC-4? In that case a value of 10 am in your python code / database will show as 6 am in the browser.

What you can try is to enter 10 am as the value in the front-end and use a print(date) in your python code to see how this value is being received by your code. Then adjust this accordingly, so if you enter 10 am in the front-end and it turns into 6 am in the python code, you change your code to date.replace(hour=6, minute=0) to adjust for this time difference.

Do keep in mind this might give some odd results if you have users from different time zones as they won't all have a four hour offset.


As a unrelated side-note: the .get() function in values.get('preferred_date') is used to gracefully return None when the value does not exists (instead of throwing an exception). But as you already checked for the existence of the value ( if 'preferred_date' in values ) you know there will be some value there and you can safely use values['preferred_date'] directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM