Reputation:
I am working a Django project. Here is my code :
today = datetime.datetime.now()
currentperiod = Day.objects.get(enddate__gte=today.date(),
startdate__lte=today.date())
And I got that message :
RuntimeWarning: DateTimeField Day.startdate received a naive datetime (2021-10-04 00:00:00) while time zone support is active.
warnings.warn("DateTimeField %s.%s received a naive datetime "
So I tried that :
today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
currentperiod = Period.objects.get(enddate__gte=today.date(),
startdate__lte=today.date())
But it does not work whereas I used pytz, I suppose it comes from today.date()
but I don't know how to proceed further ...
Could you help me please ?
Thank you very much !
Upvotes: 1
Views: 199
Reputation: 477704
A date
has no timezone info, hence that does not work by localizing. What you can do is truncate today and then add this as filtering:
today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
today = today.replace(hour=0, minute=0, second=0, microsecond=0)
currentperiod = Period.objects.get(
startdate__lte=today,
enddate__gte=today
)
If you want to check the enddate
by the end of the day, then you can work with:
from datetime import timedelta
today = datetime.datetime.now()
today = pytz.timezone("Europe/Paris").localize(today, is_dst=None)
today = today.replace(hour=0, minute=0, second=0, microsecond=0)
currentperiod = Period.objects.get(
startdate__lte=today,
enddate__gte=today + timedelta(days=1, microseconds=-1)
)
Upvotes: 1