I have this in the DB:
25.0|120|CashApp|0.0|0|1|2022-03-03 22:05:17.025000
This in the settings.py:
TIME_ZONE = 'US/Eastern' # = EST
USE_I18N = True
USE_L10N = True
USE_TZ = True
And this in the admin.py:
def timestamp_(self, obj):
return obj.timestamp.strftime("%d %b, %I:%M %p") # :%S
timestamp_.admin_order_field = 'timestamp'
And on the page it's displayed like this: 03 Mar, 10:05 PM
From what I understand it stores the timestamp in UTC in the DB, which is perfect, but why it displays it in UTC on the page? I've read that if I don't do activate(), the current timezone will be the same as default timezone, which should be EST in my case. What am I missing?
Related
I have a model that shows a short string in __str__() method of the model
def __str__(self):
return "Scheduled at %s" % (self.date_time.strftime("%B %d %Y %I:%M %p"))
#Output: <Task: Scheduled at September 30 2018 12:30 AM>
# it should have been: <Task: Scheduled at September 29 2018 08:30 PM>
When I go to the Django admin, I see in the title Task: Scheduled at September 30 2018 12:30 AM and in the input it is filled with the correct TIME_ZONE: 20:30:00
settings.py
TIME_ZONE = 'Etc/GMT+4'
USE_I18N = False
USE_L10N = False
USE_TZ = True
He keeps showing time with UTC time zone, however I set TIME_ZONE='Etc/GMT+4 in my settings.
I want time data to be saved in database as UTC and show them with TIME_ZONE, in my case Etc/GTM+4
Django converts datetimes when displaying values with templates. If you want to do the conversion in arbitrary blocks of code, use the localtime() helper:
from django.utils.timezone import localtime
def __str__(self):
return "Scheduled at %s" % localtime(self.date_time).strftime("%B %d %Y %I:%M %p")
Not able to change TImezone in Trunc functions. It always take timezone from settings.py
import pytz
ind = pytz.timezone('Asia/Calcutta')
Query:
queryset = Order.objects.annotate(date=TruncDate('created_at', tzinfo=ind)).values('date')
While inspecting sql query by queryset.query
SELECT DATE(CONVERT_TZ(`nm_order`.`created_at`, 'UTC', UTC)) AS `date` FROM `nm_order`
Reference: Trunc in Django
But for Extract, it's get working
ORM:
queryset = Order.objects.annotate(date=ExtractDay('created_at',tzinfo=ind)).values('date')
Query:
SELECT EXTRACT(DAY FROM CONVERT_TZ(`nm_order`.`created_at`, 'UTC', Asia/Calcutta)) AS `date` FROM `nm_order`
Am I miss something in Trunc ?
TimeZone Settings in my settings.py
IME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
You need to use TruncDay() instead of TruncDate. In the usage example just below that section of the documentation you'll see the difference between the two.
TruncDate does not take a timezone option - it uses the current timezone and gives you the date in that timezone.
I think the distinction between the two is that TruncDate returns a DateField which by definition cannot be timezone-aware. TruncDay on the other hand returns a DateTimeField(with time portion set to 00:00:00), which can be timezone aware.
From django 3.2, TruncDate now accepts tzinfo parameter. https://docs.djangoproject.com/en/dev/ref/models/database-functions/#django.db.models.functions.TruncDate
After Inspecting TruncDate Class looks like it doesn't have timezone option
class TruncDate(TruncBase):
kind = 'date'
lookup_name = 'date'
#cached_property
def output_field(self):
return DateField()
def as_sql(self, compiler, connection):
# Cast to date rather than truncate to date.
lhs, lhs_params = compiler.compile(self.lhs)
tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
lhs_params.extend(tz_params)
return sql, lhs_params
The time that is being inserted in database is default UTC, not the timezone based time..I do not understand why is this happening, even though I am particularly specifying, in the query, the time that I want to be inserted.
In my Model I have
class leave(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
In my settings I have
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
In my views i am setting timezone based on employee country
if employees.objects.get(emp_id=request.user.username).emp_loc == 'IND':
tzone=pytz.timezone('Asia/Calcutta')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MLA':
tzone=pytz.timezone('Asia/Manila')
elif employees.objects.get(emp_id=request.user.username).emp_loc == 'MPLS':
tzone=pytz.timezone('CST6CDT')
And then I am creating leave and updating timezone based on country
new_leave = leave.objects.create(employee=employees.objects.get(emp_id = userid.emp_id), start_date=sdt, end_date=edt, ltype=ltyp, message=des,date_created=datetime.now(tzone))
new_leave.save()
Thanks in Advance.
You can create a middleware that handles the conversion of date and time,
import pytz
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
tzname = request.session.get('django_timezone')
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
and then you can as easily create the view with the conditions that you indicated earlier.
Best if you read the documentation as Kevin suggested.
in settings.py I use:
TIME_ZONE = 'Europe/Moscow'
USE_I18N = True
USE_L10N = True
USE_TZ = True
On page.html:
{% now "jS F Y H:i" %}
And I see 25th December 2014 22:40, but now is 21:40. The same problem with auto_now_add=True in models fields - I have wrong time (hour+1).
How to fix that?
Thanks!
I'm using Django 1.6 and I have to display a date. The timezone is Guayaquil (-05:00) and I have to get the date as:
{
'fecha': partido.fecha.strftime("%d %B"),
'hora': partido.fecha.strftime("%T"),
}
Expecting: '13 Junio' and '14:00:00' respectively, since that's the time saved and in Guayaquil timezone.
However what I get is the same time in UTC and months names in english: '13 June' and '19:00:00'.
What can I do to solve this issue?
You have to configure you time zone in your Django Settings
Choices can be found Here
Check in your settings.py:
TIME_ZONE = 'America/Guayaquil'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LANGUAGE_CODE = 'es'