I am testing django 1.4 features. for me the most important is the TZ control.
I am using PG and the DateTimeField is working perfect saving the datetime having in count settings.TIME_ZONE also Im setting other differents timezones with pytz and looks good.
but the problem is with timesince tag, is ignoring the TZ:
from django.utils import timezone
from django.utils.timesince import timeuntil
class Foo(models.Model):
date = models.DateTimeField()
def remaining(self):
res = timeuntil(self.date, datetime.datetime.now(tz=timezone.get_current_timezone()))
return res
foo.remaining() is always returning the remaining count with the default timezone.
thanks in advance.
Related
I have Django model:
class Deal(models.Model):
...
created_at = models.DateTimeField(auto_now_add=True)
When I get created_at value by queryset, it always return to me the datetime value with tzinfo=<UTC> like this:
Deal.objects.filter(id=62).values('created_at')
<QuerySet [{'created_at': datetime.datetime(2015, 10, 26, 4, 10, 54, 997000, tzinfo=<UTC>)}]>
How do I force queryset return datetime value in current timezone (e.g Asia/Ho_Chi_Minh)?
Django always saves datetimes in UTC, and they are usually returned in UTC as well (depending on the database and database adapter settings). You normally select a timezone by using activate(). That affects various things, like the way datetimes are displayed in templates.
If you want to explicitly convert the timezone for some reason, you can easily do that with localtime(). For example:
from django.utils.timezone import localtime
import pytz
tz = pytz.timezone("Asia/Ho_Chi_Minh")
deals_utc = Deal.objects.filter(id=62).values("created_at")
deals_local = {"created_at": localtime(dt, tz) for dt in deals_utc.values()}
In your settings.py file, change TIME_ZONE value.
TIME_ZONE='Asia/Ho_Chi_Minh'
I am trying to set a DateTimeField for one of my django models. My code looks like this:
dt = datetime.fromtimestamp(mktime(parsed_feed.updated_parsed))
feed.updated = dt
updated_parsed is struct in the format :
time.struct_time(tm_year=2016, tm_mon=4, tm_mday=26, tm_hour=8, tm_min=20, tm_sec=43, tm_wday=1, tm_yday=117, tm_isdst=0)
And updated is obviously the django DateTimeField. I am trying to convert the struct into a datetime object, and then set it to my field. Everything works nicely, and the correct date and time is set, however, I get this error (warning) in my console:
RuntimeWarning: DateTimeField Feed.updated received a naive datetime (2016-04-26 08:25:08) while time zone support is active.
RuntimeWarning)
How do I integrate timezone support into the datetime object (dt)?
As explained in this answer:
The following line creates a naive (non-timezone aware) datetime:
creationDate = datetime.datetime.now()
Try changing that line to:
creationDate = timezone.now()
Don't forget to import timezone at the beginning of your code:
from django.utils import timezone
Use the pytz package.
So import pytz into your views.
t = pytz.timezone('Europe/Warsaw').localize(
datetime(2013, 5, 11, hour=11, minute=0))
Your timezone should be set in your settings.py
datetime and timezone conversion with pytz - mind blowing behaviour
I am writing a project with django.
I am using timezone 'Asia/ShangHai', when I am getting the datetime object, the offset of the timezone is incorrect and was:
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>
And the offset should be +8:00:00
AFAICR, the problem was not there before.
How can I solve this problem?
You can use this function with django:
def add_local_tz_to_native_time(native_dt):
# type: (datetime.datetime) -> datetime.datetime
from django.utils import timezone
if timezone.pytz is None:
return native_dt.replace(tzinfo=timezone.get_current_timezone())
else:
return timezone.get_current_timezone().localize(native_dt)
There is an API server build on top of Django. Model Author has DateTimeField which is serialised to iso formatted string, such as 2015-04-10T07:28:45.571039+00:00.
class Author(models.Model):
created = models.DateTimeField()
Client is implemented in Javascript. It builds model with given datetime field, so to update the model, I would like to use field in the same format.
To process request on server side, there is a model form
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
POST/PUT request handler raises exception: "Enter a valid date/time.". Reason for that is allowed DATETIME_INPUT_FORMATS. There is no way to accept timezone information with colon inside.
Given that I don't want to remove timezone support (USE_TZ) and would like to accept data with timezone information, what is the way to implement server side? I currently have two solutions: 1) exclude field at all 2) use CharField in form with dateutil.parser.parse function inside form clean method.
Do you have any suggestions how to deal with it?
Python (pre 3.7) can't handle an ISO8601 string with +00:00. The colon, specifically, is the problem (see: https://bugs.python.org/issue15873, https://bugs.python.org/msg169952). Django does, however, provide a solution via django.utils.dateparse.parse_datetime (see: https://stackoverflow.com/a/30449246/5043802)
To solve this problem, you can roll out your own DateTimeField that uses parse_datetime instead.
https://gist.github.com/elnygren/da7a1b7496a598f95bc8d8277f420b2d
from django import forms
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_str
from django.forms.widgets import DateTimeInput
from django.utils.translation import gettext_lazy as _, ngettext_lazy
class ISODateTimeField(forms.Field):
"""DateTimeField that uses django.utils.dateparse.parse_datetime.
More precisely, this DateTimeField accepts ISO 8601 datetime strings
that specify timezone with +00:00 syntax.
https://en.wikipedia.org/wiki/ISO_8601
https://code.djangoproject.com/ticket/11385
https://bugs.python.org/issue15873
https://bugs.python.org/msg169952
"""
widget = DateTimeInput
default_error_messages = {
'invalid': _('Enter a valid date/time.'),
}
def to_python(self, value):
value = value.strip()
try:
return self.strptime(value, format)
except (ValueError, TypeError):
raise forms.ValidationError(self.error_messages['invalid'], code='invalid')
def strptime(self, value, format):
""" stackoverflow won't let me save just an indent! """
return parse_datetime(force_str(value))
Your storage is unlikely to accept timezone aware datetimes, is your django app set up for timezones? from the docs:
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.
also if you're not using postgresql:
Other backends store datetimes without time zone information. If you
switch from USE_TZ = False to USE_TZ = True, you must convert your
data from local time to UTC – which isn’t deterministic if your local
time has DST.
Bascially it's not completely done for you just be setting USE_TZ in settings.py
i use #elnygren code and i have a bug with a form that ISODateTimeField field is not required, it tries to validate all the time, i fix this way:
def to_python(self, value):
if value in self.empty_values:
return None
value = value.strip()
for _format in self.input_formats:
try:
return self.strptime(value, _format)
except (ValueError, TypeError):
continue
raise forms.ValidationError(self.error_messages["invalid"], code="invalid")
I have a DateTimeField:
class Assignment (models.Model):
official_deadline = models.DateTimeField(null=True, blank=True)
I need to compare it to current date time, I have tried :
def official_deadline_past(self):
if datetime.datetime.today() > self.official_deadline:
return True
return False
But it returns always False I have also tried:
def official_deadline_past(self):
if datetime.datetime.now() > self.official_deadline:
return True
return False
But I have the same problem.
I have an information in the field: 2011-07-02 00:00:00 for example in the form generated by ModelForm
I had a similar issue comparing DateTimeField with datetime under python 2.7.3 and django 1.3.1
I don't think DateTimeField had good timezone support then or I didnt have it configured properly.
Whenever I specified a timezone for datetime field all my comparisons of DateTimeField > datetime would fail.
datetime was using local central time while DateTimeField was entered as eastern.
I ended up just putting a stupid hack in to add a timedelta(hours=1) to the datetime central object to "convert" it to eastern.
I have same issue , django model Datetime Field like only contain date(without time)
now = datetime.datetime.now()
q1=Q()
q1.children.append(Q(datetimefieldFrom__lte=now))
q1.children.append(Q(datetimefieldTo__gte=now))
ex.
now : "2020-12-11 17:17:58.000000"
datetimeFrom : "2020-12-11 16:17:58.000000"
datetimeFrom : "2020-12-11 18:17:58.000000"
it just pass "2020-12-11 00:00:00.000000" to compare
#johnjamesmiller, your timezone issue can be solve by modify the setting.py
TIME_ZONE = 'Asia/Hong_Kong'
USE_TZ = True