I am trying to display set time of Postgres database time to datetime field into Odoo.
I am creating field is that to set the time.
last_modify_article = fields.Datetime("Last Modify Date")
But my DateTime :~ 2017-08-28T08:43:56+0200 is perfectly stored in Postgres database but in Odoo saw in different.
So, my question is that how can I manage the database date-time in the field.
Here is the Postgres Time
And
Here is Odoo field to set datetime in UTC
Actually the database stores the Datetime field according to the system timezone. In Odoo, views which will be automatically converted according to the user's timezone if it is set.
On your images, I can see the time difference id +5:30 ie, Asia/Kolakata timezone. So your custom operations on Datetime field need the proper conversion of Timezone according to the user.
Odoo views and ORM methods are treated the tz with moment.js and the pytz conversions. This is actually a good feature to manage different timezones in Odoo.
You can use astimezone on Datetime objects:
def astimezone(self, tz): # known case of datetime.datetime.astimezone
""" tz -> convert to local time in new timezone tz """
return datetime(1, 1, 1)
or
fields.Datetime.context_timestamp(self, datetime.strptime(value, DEFAULT_SERVER_DATETIME_FORMAT))
Odoo is designed to have the date and time stored as UTC in the database and convert it to the user's timezone on the front-end.
What time zone is set for your user? You can click your name in the top right, then Preferences. Time zone should be shown on the popup form.
You can use pytz library to convert datetime based on user's timezone. See the code sample.
import pytz
import datetime
def current_user_datetime(self):
currenttimezone = pytz.timezone(self.env.context.get('tz'))
user_datetime = datetime.datetime.now(currenttimezone)
self.timefield = user_datetime
Related
I have noticed that when I return records from my SQL database using the following: the_records = records.objects.filter(datetime__contains="2015-01-15"), I get back the wrong records because the timezone is affecting the function call somehow - I know this because if I temporarily disable the timezone, the right records are returned. Can anyone offer assistance on what I should do to fix this problem (I still need to use the timezone).
Regards, Mark
I'm assuming that datetime is a Django DateTime field, and you're trying to get the results that have a value that matches the date '2015-01-15', ignoring the actual time.
In that case, you probably want to do a date query, like: Records.objects.filter(datetime__date=datetime.date(2015, 1, 15))
If you need to query your db with a timezone specific date, you can just create a datetime object that is aware of it's timezone.
Example:
# Get your timezone
from django.utils import timezone
my_timezone = timezone.get_current_timezone()
# Get create your timezone aware datetime object
from datetime import datetime
query_date = datetime(2015,01,15).replace(tzinfo=my_timezone)
# now you can run your query with a timezone specific datetime object
the_records = records.objects.filter(datetime=query_date)
This should solve your issue and get you the accurate results you need.
Please let me know if you still have any questions.
This link has more info related to django timezones if you are interested in learning more.
I am trying to set expire_time in my django model to be midnight of user's selected date with timezone aware. But I am not able to get it properly. Can anyone tell me how I can do it or where I am making mistake in my code?
My codes are,
date = datetime.strptime(str(request.POST.get('expire') + ', 23:59:59'),
'%Y-%m-%d, %H:%M:%S')
tz = timezone.get_current_timezone()
date_tz = tz.localize(date)
createEventInDB.ev_expire = date_tz
try:
createEventInDB.save()
except Exception as e:
error = e
So if I select date which is December 1st 2015, it would be posting as 2015-12-1
I want to save data in database like 2015-12-01 23:59:59. I want to give whole day to user. My current timezone is America/Chicago. I have set active timezone by ip. So I want to make it like user can post from anywhere but timezone must be UTC aware and expire at midnight. Can anyone tell me how can I make it possible?
based on the documentation at https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/
When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms.
So all this is completely unnecessary and all you need to do is use the models.DateTimeField like you always did.
You can define a Date widget in the view or form and alter Time of DateTimeField later on to 23:59:59 before saving (or you can provide it as a default) and Django will automatically convert it to UTC before saving.
I want to do is 2015-12-01 23:59:59 utc
Your code in the question returns 23:59:59 in the current time zone.
It is even simpler to return "23:59:59 UTC" instead given the corresponding UTC date:
from datetime import datetime
import pytz
ev_expire = datetime(utc_date.year, utc_date.month, utc_date.day, 23, 59, 59,
tzinfo=pytz.utc)
I want to format a datetime to the user's localtime. I do not want to do it in a template though, I want to do it in the .py file and pass it to the template for display as is. What facility do the template code use to do this? Can I get at this from my .py file?
You need to start using Django's Time Zones:
set USE_TZ to True
install pytz module (recommended)
set the default TIME_ZONE
Then, in order to make time-zone-aware datetimes, you need to somehow determine the user's timezone. The most reliable way would be to let the user choose the timezone and remember the choice for every user. Then, in the view activate the specific user's timezone:
import pytz
from django.utils import timezone
tzname = request.session.get('django_timezone') # or wherever you store the user's timezone
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
print timezone.now()
Also see:
Selecting the current time zone (has the view-to-template example)
When should I activate/deactivate the current timezone in Django (1.4)?
How do I get the visitor's current timezone then convert timezone.now() to string of the local time in Django 1.4?
Hope that helps.
I have a datetime object that is set to 2014-02-24 19:00:00+00:00 and I believe this is set as UTC by default (through the Django admin panel).
This time is actually Africa/Johannesburg, so I convert it like this:
local_timezone= pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.replace(tzinfo=local_timezone)
This will now output 2014-02-24 19:00:00+01:30
Now I want to store this as the converted UTC timezone, so I do it like this:
utc_time = local_time_start.astimezone(utc)
For some reason, this outputs 2014-02-24 17:30:00+00:00. The time is should output is 17:00:00 so where is the extra 30 mins coming from?
Basically I am trying to take the given input from the django admin panel as the local timezone of the models time_zone field, but store it as UTC.
Is there a better way I can approach this? The Django docs explain how to convert the users local timezone but I need to convert it based on the timezone in the models attributes.
Don't use datetime.replace() with pytz timezones. The pytz timezones contain historical timezone data (to allow for dates in the past to use the right offsets from UTC), but datetime.replace() cannot use the correct information in that case.
Use the timezone.localize() method instead:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix)
See the pytz documentation.
Use this only on non-timezone-aware objects. For timezone aware datetime values, use datetime.astimezone() to translate value from one timezone to another:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = self.start_time_unix.astimezone(local_timezone)
If you have a datetime value that has the wrong timezone attached (it should represent the given time in a different timezone, not a different time in that timezone), remove the old timezone first using .replace(tzinfo=None), then usetimezone.localize()`:
local_timezone = pytz.timezone("Africa/Johannesburg")
local_time_start = local_timezone.localize(self.start_time_unix.replace(tzinfo=None))
In OpenERP, when I try to print the current date and time, it always print the 'UTC' time. But I want to get time in the user timezone . Each user have different timezone.For example 'CST6CDT', 'US/Pacific' or 'Asia/Calcutta'. So I need to get time in user timezone so that I can show the correct datetime in the report. I have tried to change the timezone using localize() and replace() function in datatime module. But I didn't get the correct output.
Got it.
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(fmt)
# Convert to US/Pacific time zone
now_pacific = now_utc.astimezone(timezone('US/Pacific'))
print now_pacific.strftime(fmt)
# Convert to Europe/Berlin time zone
now_berlin = now_pacific.astimezone(timezone('Europe/Berlin'))
print now_berlin.strftime(fmt)
Courtesy: http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
As of OpenERP 6.1 the timezone of all Python operations happening on the server-side (and in modules) is forced to be UTC. This was a design decision explained in various places [1]. The rendering of datetime values in the user's timezone is meant to be done on the client-side exclusively.
There are very few cases where it makes sense to use the user's timezone instead of UTC on the server-side, but indeed printing datetime values inside reports is one of them, because the client-side will have no chance to convert the contents of the resulting report.
That's why the report engine provides a utility method for doing so: the formatLang() method that is provided in the context of reports (RML-based ones at least) will format the date according to the timezone of the user if you call it with a datetime value and with date_time=True (it uses the tz context variable passed in RPC calls and based on the user's timezone preferences)
You can find example of how this is used in the official addons, for example in the delivery module (l.171).
Have a look at the implementation of formatLang() if you want to know how it actually does the conversion.
[1]: See the OpenERP 6.1 release notes, this other question, as well as comment #4 on bug 918257 or bug 925361.
from: http://help.openerp.com/question/30906/how-to-get-users-timezone-for-python/
DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
import pytz
from openerp import SUPERUSER_ID
# get user's timezone
user_pool = self.pool.get('res.users')
user = user_pool.browse(cr, SUPERUSER_ID, uid)
tz = pytz.timezone(user.context_tz) or pytz.utc
# get localized dates
localized_datetime = pytz.utc.localize(datetime.datetime.strptime(utc_datetime,DATETIME_FORMAT)).astimezone(tz)
DateInUTC = <~ Time variable to convert
To convert to user's timezone:
LocalizedDate = fields.datetime.context_timestamp(cr, uid, DateInUTC, context=context)
To remove the offset:
LocalizedDate = LocalizedDate.replace(tzinfo=None)