104👍
✅
According to timezone.now()
source:
def now():
"""
Returns an aware or naive datetime.datetime, depending on settings.USE_TZ.
"""
if settings.USE_TZ:
# timeit shows that datetime.now(tz=utc) is 24% slower
return datetime.utcnow().replace(tzinfo=utc)
else:
return datetime.now()
It’s based on utc
instead of your default timezone. You could achieve same value by using
now = timezone.make_aware(datetime.datetime.now(),timezone.get_default_timezone())
print now.astimezone(timezone.utc)
👤okm
37👍
Since Django 1.11 you can simply call django.utils.timezone.localtime
to fetch datetime
for your default timezone.
>>> from django.utils import timezone
>>> timezone.localtime()
From docs:
Converts an aware datetime to a different time zone, by default the current time zone.
When value is omitted, it defaults to
now()
.This function doesn’t work on naive datetimes; use
make_aware()
instead.
- [Django]-Choose test database?
- [Django]-How can I programmatically obtain the max_length of a Django model field?
- [Django]-How to do math in a Django template?
6👍
You can pass a param to datetime.datetime.now()
:
import pytz, datetime
utc = pytz.utc
utc_now = datetime.datetime.now(tz=utc)
Or use timezone
, a la:
from django.utils import timezone
now = timezone.now()
https://docs.djangoproject.com/en/2.1/topics/i18n/timezones/
- [Django]-Django Queryset with year(date) = '2010'
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
5👍
from datetime import datetime
from django.utils import timezone
def now():
try:
return timezone.localtime(timezone.now()).strftime('%Y-%m-%dT%H:%M:%S')
except Exception as exp:
print('TimeZone is not set - {}'.format(exp))
return datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
If you set TIME_ZONE = 'Europe/London'
and USE_TZ = True
in Django setting, it runs the try
section, otherwise it runs the except
section.
[NOTE]:
.strftime()
is an option
- [Django]-Django Rest framework, how to include '__all__' fields and a related field in ModelSerializer ?
- [Django]-Django signals vs. overriding save method
- [Django]-Best practices for adding .gitignore file for Python projects?
0👍
from datetime import datetime
from pytz import timezone
# one can get any time for respective timezone
current_time = datetime.now(timezone('Asia/Kolkata'))
print("time in india :", current_time)
- [Django]-Django admin: how to sort by one of the custom list_display fields that has no database field
- [Django]-Check if OneToOneField is None in Django
- [Django]-Adding css class to field on validation error in django
Source:stackexchange.com