310π
By default, the datetime
object is naive
in Python, so you need to make both of them either naive or aware datetime
objects. This can be done using:
import datetime
import pytz
utc=pytz.UTC
challenge.datetime_start = utc.localize(challenge.datetime_start)
challenge.datetime_end = utc.localize(challenge.datetime_end)
# now both the datetime objects are aware, and you can compare them
Note: This would raise a ValueError
if tzinfo
is already set. If you are not sure about that, just use
start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)
BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following
d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
year=d.year,
month=d.month,
day=d.day,
hour=d.hour,
minute=d.minute,
second=d.second,
tzinfo=pytz.UTC)
170π
datetime.datetime.now
is not timezone aware.
Django comes with a helper for this, which requires pytz
from django.utils import timezone
now = timezone.now()
You should be able to compare now
to challenge.datetime_start
- [Django]-Charts in django Web Applications
- [Django]-Celery missed heartbeat (on_node_lost)
- [Django]-How can i test for an empty queryset in Django?
133π
One line of code solution
if timezone_aware_var <= datetime.datetime.now(timezone_aware_var.tzinfo):
pass #some code
Explained version
# Timezone info of your timezone aware variable
timezone = your_timezone_aware_variable.tzinfo
# Current datetime for the timezone of your variable
now_in_timezone = datetime.datetime.now(timezone)
# Now you can do a fair comparison, both datetime variables have the same time zone
if your_timezone_aware_variable <= now_in_timezone:
pass #some code
Summary
You must add the timezone info to your now()
datetime.
However, you must add the same timezone of the reference variable; that is why I first read the tzinfo
attribute.
- [Django]-How to merge consecutive database migrations in django 1.9+?
- [Django]-__init__() got an unexpected keyword argument 'mimetype'
- [Django]-Best practices for getting the most testing coverage with Django/Python?
55π
Disable time zone.
Use challenge.datetime_start.replace(tzinfo=None);
You can also use replace(tzinfo=None)
for other datetime.
if challenge.datetime_start.replace(tzinfo=None) <= datetime.now().replace(tzinfo=None) <= challenge.datetime_end.replace(tzinfo=None):
- [Django]-Multiple Database Config in Django 1.2
- [Django]-'staticfiles' is not a valid tag library: Template library staticfiles not found
- [Django]-How can I access environment variables directly in a Django template?
14π
no third-party, only the native datetime module.
from datetime import datetime, timedelta, timezone
time1 = datetime.strptime('2021-07-15T00:22:02+0000', '%Y-%m-%dT%H:%M:%S%z')
time2 = datetime(2021, 7, 15, tzinfo=timezone(offset=timedelta()))
if time1 < time2:
print(True)
- [Django]-How do Django models work?
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
- [Django]-Django.db.utils.ProgrammingError: relation "bot_trade" does not exist
4π
It is working form me.
Here I am geeting the table created datetime and adding 10 minutes on the datetime.
later depending on the current time, Expiry Operations are done.
from datetime import datetime, time, timedelta
import pytz
Added 10 minutes on database datetime
table_datetime = β2019-06-13 07:49:02.832969β (example)
# Added 10 minutes on database datetime
# table_datetime = '2019-06-13 07:49:02.832969' (example)
table_expire_datetime = table_datetime + timedelta(minutes=10 )
# Current datetime
current_datetime = datetime.now()
# replace the timezone in both time
expired_on = table_expire_datetime.replace(tzinfo=utc)
checked_on = current_datetime.replace(tzinfo=utc)
if expired_on < checked_on:
print("Time Crossed)
else:
print("Time not crossed ")
It worked for me.
- [Django]-Django Template Language: Using a for loop with else
- [Django]-How to check if ManyToMany field is not empty?
- [Django]-Django Admin app or roll my own?
4π
To make your datetime object timezone aware from naive, simply add the function:
datetimeObject.astimezone()
- [Django]-How to test Django's UpdateView?
- [Django]-Using the reserved word "class" as field name in Django and Django REST Framework
- [Django]-Django: sqlite for dev, mysql for prod?
2π
You are trying to set the timezone for date_time which already has a timezone.
Use replace
and astimezone
functions.
local_tz = pytz.timezone('Asia/Kolkata')
current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)
- [Django]-How does one make logging color in Django/Google App Engine?
- [Django]-Ignoring Django Migrations in pyproject.toml file for Black formatter
- [Django]-Django: For Loop to Iterate Form Fields
1π
So the way I would solve this problem is to make sure the two datetimes are in the right timezone.
I can see that you are using datetime.now()
which will return the systems current time, with no tzinfo set.
tzinfo is the information attached to a datetime to let it know what timezone it is in. If you are using naive datetime you need to be consistent through out your system. I would highly recommend only using datetime.utcnow()
seeing as somewhere your are creating datetime that have tzinfo associated with them, what you need to do is make sure those are localized (has tzinfo associated) to the correct timezone.
Take a look at Delorean, it makes dealing with this sort of thing much easier.
- [Django]-Adding to the "constructor" of a django model
- [Django]-Django REST framework post array of objects
- [Django]-How can I get MINIO access and secret key?
1π
If you are using SQLAlchemy
and storing the DateTime then you can store it with timezone info. This will allow you to compare that DateTime with timezone-aware DateTimes. Example Column definition in SQLAlchemy core
:
Column("created_at", DateTime(timezone=True), nullable=False)
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Iterating over related objects in Django: loop over query set or use one-liner select_related (or prefetch_related)
- [Django]-How to use pdb.set_trace() in a Django unittest?
1π
If youβre using Python 3.6 and newer, you can leverage the native datetime
capability.
utc_date = datetime.datetime.fromtimestamp(0, datetime.timezone.utc)
- [Django]-How to get the name of current app within a template?
- [Django]-Problems extend change_form.html in django admin
- [Django]-Django: Record with max element
0π
In my case I have controlled the time zone with pytz and I have converted the date to native with timezone from django.utils:
import pytz
from django.utils import timezone
def _my_method(native_date, timezone):
aware_date = datetime.now(pytz.timezone(timezone))
return timezone.make_naive(aware_date) > native_date
Also you can make aware the native date with timezone.make_aware
- [Django]-Speeding up Django Testing
- [Django]-Django admin TabularInline β is there a good way of adding a custom html column?
- [Django]-Django models avoid duplicates
0π
From time to time this error pops up in my notebooks⦠I have no clue why.
My datetime objects are usually in arrays. I tried some of the answers above, but the way I found to deal with this problem is
import numpy as np
import matplotlib.dates as mdates
array_with_datetime = np.array(
mdates.num2date(
mdates.date2num(
array_with_datetime)))
not elegant, but it works. If I not use the np.array
, it returns a list.
- [Django]-Django datefield filter by weekday/weekend
- [Django]-Http POST drops port in URL
- [Django]-Django, Turbo Gears, Web2Py, which is better for what?
-2π
Just:
dt = datetimeObject.strftime(format) # format = your datetime format ex) '%Y %d %m'
dt = datetime.datetime.strptime(dt,format)
So do this:
start_time = challenge.datetime_start.strftime('%Y %d %m %H %M %S')
start_time = datetime.datetime.strptime(start_time,'%Y %d %m %H %M %S')
end_time = challenge.datetime_end.strftime('%Y %d %m %H %M %S')
end_time = datetime.datetime.strptime(end_time,'%Y %d %m %H %M %S')
and then use start_time
and end_time
- [Django]-Get user profile in django
- [Django]-Django REST Framework (DRF): Set current user id as field value
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?