Django automatically converting datetime string to local timezone - python

I am adding timestamp in my payload and storing it in the database for every record.
Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}]
This is how I process it.
content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True)
My model has timestamp field as :
timestamp = models.DateTimeField(null=True)
When I check in my database it stores timestamp field as :
2017-12-12 13:35:30
Which should be stored as it is as per my requirement. 2017-12-12 08:05:30
i.e it stores the timestamp field + my local timezone(+5:30) hours.
I want it to store the timestamp field as it is.
I tried other posts where they suggest using del os.environ['TZ'].
Any idea what I may have done which causes this or what could I do to avoid this.
Any help is appreciated.

So according to this Question the problem is when django converts datetime to postgres timestamptz in the database.
Postgres prevent timestamp with timezone conversion
So I need to have timestamp field in PostgreSQL
In order to do that , I need to use the answer posted in this question.
Can we have django DatetimeField without timezone?
Where I need to specify USE_TZ = False in the settings.
This makes sure while migrating PostgreSQL considers datetimefield to be converted to timestamp and not timestamptz .

You can set a timezone in settings.py
Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Asia/Calcutta'
for UTC+05:30
Reference from Selcuk Answer

Related

save Jalali(Hijri shamsi) datetime in database in django

I have a Django project, and I want to save created_at datetime in the database. I generate datetime.now with jdatetime (or Khayyam) python package and try to save this in DateTimeField. But sometimes it raises error because the Gregorian(miladi) date of the entry does not exist. what can I do about this?
In my idea, you can save two model fields.
One is DateTimeField contains gregorian datetime, and
another one, CharField contains converted Jalali to a String value and save it.
The DateTimeField for functionality, e.g., filter between to datetime.
The StringField for representing in response(without overload).

Convert datetime to local time from Django Query to Openpyxl

Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl.
Right now, I simply assign the attribute of the query to the cell.
query = SomeModel.objects.latest()
date_recorded = query.date_recorded
In templates, date_recorded is already converted to local time. No problem there.
ws.cell(row=rows, column=cols).value = date_recorded
The above code results to UTC. Please help me convert it to local time. Thank you.
I am using pytz python package.
import pytz
# UTC to IST
time_zone = pytz.timezone('Asia/Kolkata') # set timezone here
date_recorded = time_zone.localize(query.date_recorded)

How to set Postgres Datetime field into Odoo Datetime field

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

SQL Where Clause and Django Timezone

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.

Django : get entries of today and SplitDateTime Widget?

I used : SplitDateTimeWidget to split DateTime field ,
appointment = forms.DateTimeField(widget=forms.SplitDateTimeWidget)
In the template side i manage to use datePicker and TimePicker for each field , using jQuery .
When i try to filter the entries regarding to today date as in this code :
d = datetime.date.today()
entries = Entry.objects.filter(appointment__year=d.year ,appointment__month=d.month ,appointment__day=d.day )
It shows the entries of yesterday 17 aug :( which is really weird !
I Tried to split the Date and Time in the model , i got the same result as well !
Any idea how to fix this ?!
Fix your timezone settings, in settings.py TIME_ZONE
Default: 'America/Chicago'
Some excerpts of useful info from the docs:
A string representing the time zone
for this installation. See available
choices.
(...)
Note that this is the time zone to which Django will convert all
dates/times -- not necessarily the
timezone of the server.
(...)
Django cannot reliably use alternate
time zones in a Windows environment.
If you're running Django on Windows,
this variable must be set to match the
system timezone.

Categories