4👍
✅
You should add tz_info
to the datetime
object before passing to the model instance.
import pytz
import datetime
import time
from django.conf import settings
def ctodatetime(ctimeinput):
etime = time.ctime(int(ctimeinput))
btime = datetime.datetime.strptime(etime, "%a %b %d %H:%M:%S %Y")
tz_aware_datetetime = btime.replace(tzinfo=pytz.timezone(settings.TIME_ZONE))
print(tz_aware_datetetime)
return tz_aware_datetetime
The .replace()
function returns a new datetime object
For more info, refer this SO post RuntimeWarning: DateTimeField received a naive datetime
👤JPG
1👍
A Django-specific solution could be using django.utils.timezone
, in the following manner:
from datetime import datetime
from django.utils import timezone
from django.conf import settings
def ctodatetime(ctimeinput):
etime = time.ctime(int(ctimeinput))
btime = datetime.strptime(etime, "%a %b %d %H:%M:%S %Y")
tz = getattr(settings, 'TIME_ZONE', None)
return timezone.make_aware(btime, tz)
This relies on the fact that btime
will be a naive timestamp, and makes use of Django’s make_aware() to convert it to a timezone-aware timestamp.
- [Django]-Django 1.9 URLField removing the necessary http:// prefix
- [Django]-Unable to connect to gmail smtp linode django apache2 setup
- [Django]-Django rest framework router not found
Source:stackexchange.com