Reputation: 11
I need to set a value to the system datetime in my code. In settings.py in the django application, I have commented TIME_ZONE and USE_TZ= True.
And in my file the code looks like:
import datetime
checkedin_dt = datetime.datetime.now()
logger.info(checkedin_dt) # -- gives me a value that is utc-5:00
However, when I run the same thing in the python terminal, it gives me the correct systemdatetime. I want my code to fetch the systemdatetime without setting any specific timezone in settings.py
Any idea why this isn't working in the code. The db is sqlite and the application is a django application.
Upvotes: 1
Views: 163
Reputation: 48952
Django doesn't include a way to determine the system time zone, but you can use the tzlocal package for that.
I've never tried it myself, but I think you could get what you want by doing the following in your settings file:
from tzlocal import get_localzone
TIME_ZONE = get_localzone().zone
It could still fail if the name of the timezone can't be determined, since TIME_ZONE
must be a string name.
Upvotes: 0
Reputation: 2873
Set USE_TZ = True
and use timezone()
:
from django.utils import timezone
checkedin_dt = timezone.now()
Documentation: https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/
Upvotes: 1