67👍
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
0👍
If we look at the source code, django.utilts.timezone.now
is precisely datetime.datetime.now
only with the timezone set to UTC. So if you want to make it work with datetime
, then use the following:
import datetime
creationDate = datetime.datetime.now(datetime.timezone.utc)
If you got the warning when setting a specific datetime (not now
), then pass the tzinfo
using whatever timezone it should be. If it’s UTC it’s pretty straightforward, just pass datetime.timezone.utc
.
creationDate = datetime.datetime(2022, 10, 7, 11, 31) # <--- RuntimeWarning: DateTimeField received a naive datetime ...
creationDate = datetime.datetime(2022, 10, 7, 11, 31, tzinfo=datetime.timezone.utc) # <--- no warning
If the datetime should be in specific timezone, then since Python 3.9, zoneinfo
module, which provides implementation to support the IANA time zone database, is in the standard library. So for example, if the timezone should be Tokyo (or UTC+09:00), then one could use the following.
from zoneinfo import ZoneInfo
creationDate = datetime.datetime(2022, 10, 7, 11, 31, tzinfo=ZoneInfo("Asia/Tokyo"))
On the other hand, if you got
TypeError: expected string or buffer
or
fromisoformat: argument must be str
see if you forgot to call the function e.g. timezone.now()
/datetime.datetime.now()
and instead passed the function itself e.g. timezone.now
.
- [Django]-Django: is there a way to count SQL queries from an unit test?
- [Django]-Django Admin: how to display fields from two different models in same view?
- [Django]-Link in django admin to foreign key object