Django DateTimeField to compare with datetime.now() - python

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

Related

How do I force Django queryset return datetime field in current timezone?

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'

Set UTC when fixing naive datetimes with django.utils.timezone?

I'm using Django 1.9. I have a model with a DateTimeField:
class myModel(models.Model):
created = models.DateTimeField(blank=True, null=True)
And I have some naive text datetimes that look like this:
str = "2017-05-18T16:38:23"
If I do this:
d = datetime.strptime(result['last_modified'],
"%Y-%m-%dT%H:%M:%S")
mymodel.last_modified = dt_aware
I get a warning:
RuntimeWarning
439
/usr/local/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1430:
RuntimeWarning: DateTimeField CV.last_modified received a
naive datetime (2015-04-07 09:09:20) while time zone support
is active.
So I'm trying this instead, but I'm aware that instead of current timezone I should really be using UTC, because I know the datestrings are UTC:
d = datetime.strptime(str, "%Y-%m-%dT%H:%M:%S")
dt_aware = tz.make_aware(d, tz.get_current_timezone())
mymodel.last_modified = dt_aware
How can I amend this to use UTC rather than current timezone? I don't want to disable timezone support in my app.

Django DateTime field received a naive datetime

I've seen this question asked a few times and I have followed the answers suggested, however im still getting the error:
/usr/lib64/python2.7/site-packages/django/db/models/fields/__init__.py:1430: RuntimeWarning: DateTimeField CircuitMaintenance.end_time received a naive datetime (2017-02-24 23:59:59) while time zone support is active.
RuntimeWarning)
From what ive read using django utils timezone instead of datetime.now() should of solved the issue, but it has not. I have also got the following settings in my settings.py
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
code
from django.utils import timezone
dt_now = timezone.now()
days_away = datetime(dt_now.year, dt_now.month, dt_now.day) + timedelta(days)
days_away_end = days_away + timedelta(hours=23,minutes=59,seconds=59)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=days_away, end_time__lte=days_away_end,circuit__site_data__site_type="Major Site")
Probably because the timezone info is lost when creating days_away. You can simply add timezone.now() to a timedelta:
days_away = timezone.now() + timedelta(days)
To default time data to midnight, you can use replace:
days_away = timezone.now().replace(hour=0,minute=0, second=0) + timedelta(days)
Also, note that what you have is a warning, not an error.

django time zone aware setup return local datetime in query

I have a django 1.5 setup with
TIME_ZONE = 'Asia/Jerusalem'
USE_TZ = True
in my settings file. I always set my datetime fields with tz aware datetime.
however when querying an object with models.DateTimeField
root.alert_set.all()
I get a local datetime instead of a tz aware one.
any ideas?
Thanks,
Shy

django timeuntil ignoring timezone

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.

Categories