I used : SplitDateTimeWidget to split DateTime field ,
appointment = forms.DateTimeField(widget=forms.SplitDateTimeWidget)
In the template side i manage to use datePicker and TimePicker for each field , using jQuery .
When i try to filter the entries regarding to today date as in this code :
d = datetime.date.today()
entries = Entry.objects.filter(appointment__year=d.year ,appointment__month=d.month ,appointment__day=d.day )
It shows the entries of yesterday 17 aug :( which is really weird !
I Tried to split the Date and Time in the model , i got the same result as well !
Any idea how to fix this ?!
Fix your timezone settings, in settings.py TIME_ZONE
Default: 'America/Chicago'
Some excerpts of useful info from the docs:
A string representing the time zone
for this installation. See available
choices.
(...)
Note that this is the time zone to which Django will convert all
dates/times -- not necessarily the
timezone of the server.
(...)
Django cannot reliably use alternate
time zones in a Windows environment.
If you're running Django on Windows,
this variable must be set to match the
system timezone.
Related
I am adding timestamp in my payload and storing it in the database for every record.
Suppose say a part of my payload is {"content":[{"timestamp":"2017-12-12 08:05:30"}]
This is how I process it.
content['timestamp'] = parser.parse(content['timestamp'],dayfirst=True)
My model has timestamp field as :
timestamp = models.DateTimeField(null=True)
When I check in my database it stores timestamp field as :
2017-12-12 13:35:30
Which should be stored as it is as per my requirement. 2017-12-12 08:05:30
i.e it stores the timestamp field + my local timezone(+5:30) hours.
I want it to store the timestamp field as it is.
I tried other posts where they suggest using del os.environ['TZ'].
Any idea what I may have done which causes this or what could I do to avoid this.
Any help is appreciated.
So according to this Question the problem is when django converts datetime to postgres timestamptz in the database.
Postgres prevent timestamp with timezone conversion
So I need to have timestamp field in PostgreSQL
In order to do that , I need to use the answer posted in this question.
Can we have django DatetimeField without timezone?
Where I need to specify USE_TZ = False in the settings.
This makes sure while migrating PostgreSQL considers datetimefield to be converted to timestamp and not timestamptz .
You can set a timezone in settings.py
Here is the list of valid timezones:
http://en.wikipedia.org/wiki/List_of_tz_database_time_zones
You can use
TIME_ZONE = 'Asia/Calcutta'
for UTC+05:30
Reference from Selcuk Answer
Django converts the date time (I use timezone.now() to store in database) to local time in templates fine. What I need help on is when it is written to a cell in openpyxl.
Right now, I simply assign the attribute of the query to the cell.
query = SomeModel.objects.latest()
date_recorded = query.date_recorded
In templates, date_recorded is already converted to local time. No problem there.
ws.cell(row=rows, column=cols).value = date_recorded
The above code results to UTC. Please help me convert it to local time. Thank you.
I am using pytz python package.
import pytz
# UTC to IST
time_zone = pytz.timezone('Asia/Kolkata') # set timezone here
date_recorded = time_zone.localize(query.date_recorded)
As long as I'm using plain ol' Python shell, the datetime.datetime.now() command works fine to get system's local (non-UTC) time.
But I'm working on a Django project where the time zone is changed in settings.py with TIME_ZONE = 'UTC'.
I've tried many solutions from django.utils timezone to tzlocal module, but none of them works. All of them return either incorrect or UTC time.
All of the solutions work if I change the timezone in settings.py to my local timezone. But I can't do that, so is there any way to bypass the default timezone option in settings.py? Or any way the settings.py's timezone can be automatically updated? If I remove the TIME_ZONE line, I don't know why, but it seems to get a random timezone.
EDIT -
I know that the timezone can be entered manually with pytz, but I don't want to do that. I want to get the local system timezone, but WITHOUT Django's moderation of the timezone.
Thanks.
Django seems to be putting its timezone in the TZ environment variable. Try del os.environ['TZ'] then using tzlocal.
To get the time for a different timezone, use this code:
# create another timezone instance
import pytz
new_york_tz = pytz.timezone("America/New_York")
# get the current date and time, with the timezone set in your settings.py
from django.utils import timezone
d = timezone.now()
print(d)
# get the date and time in your other timezone
d2 = new_york_tz.normalize(d)
print(d2)
See: https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/#naive-and-aware-datetime-objects
You can use Javascript to get the Timezone Offset from browser to UTC. Here is the code.
var d = new Date()
var n = d.getTimezoneOffset()
alert(n)
The result is the amount of minutes. For example, you will get 480 in Los Angeles. if the result is negative number, the timezone should be the "West", opposite, the positive number means "East". AND 1 timezone = 60 minutes, so, you can figure out 480 / 60 = 8. Then the result is Los Angeles is in the west 8 timezone. Then you can use pytz to get the local time.
I am working on Django based website. I am trying to get correct timezone and time to be displayed. But it is not working properly. I live in Dallas, Texas. So my default timezone is 'America/Chicago'.
My settings.py file has these lines of code.
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
I have datetime, and pytz installed. So when I am trying to save time in database, my codes are,
from datetime import datetime
import pytz
utc = pytz.utc
database = Database.objects.get(id=1)
databas.time = utc.localize(datetime.now())
database.save()
so when I check into database, updated time is 2015-10-20 23:13:04
instead of 2015-10-20 18:13:04
and when I print it out in template by codes below, I get this output Oct. 20, 2015, 1:13 p.m.
{{ database.time|localtime }}
I am confused how to use datetime, pytz and all to get accurate time along with settings.py file.
What I want to do is I want to save UTC time. But when I print out I want to get visitor's timezone and print time according to user. My website will be accessible only in United States for now. My model has
time = models.DateTimeField(auto_now_add=True)
and it is saving some different time. I have another model where I have column named expire time where I am using following codes to save,
expire_time = utc.localize(datetime.now()+ timedelta(hours=24))
means I want to expire a link after 24 hours. But this timezone is confusing me. Can anyone help me? I don't know what should I use in my codes to get proper timezone.
If you set USE_TZ = True Django stores datetimes in UTC. Use the following to create a timezone aware datetime.now:
from django.utils import timezone
from datetime import timedelta
database.time = timezone.now()
expire_time = timezone.now() + timedelta(hours=24)
You can then use activate() to set the current time zone to the end user’s actual time zone.
Have a look at "Selecting the current time zone" to see an example how a user can select his timezone and how this selection is used to activate his timezone.
I'm trying to figure out what's going on with a timezone conversion that's happening in Django.
My view code is as below, it filters on a date range and groups on the day of creation:
def stats_ad(request):
start_date = datetime.datetime.strptime(request.GET.get('start'), '%d/%m/%Y %H:%M:%S')
end_date = datetime.datetime.strptime(request.GET.get('end'), '%d/%m/%Y %H:%M:%S')
fads = Ad.objects.filter(created__range=[start_date, end_date]).extra(select={'created_date': 'created::date'}).values('created_date').annotate(total=Count('id')).order_by("created_date")
The SQL query that is produced by django when I set the get variable of start to "01/05/2013 00:00:00" and the request end variable to "11/05/2013 23:59:00":
SELECT (created::date) AS "created_date", COUNT("ads_ad"."id") AS "total" FROM "ads_ad" WHERE "ads_ad"."created" BETWEEN E'2013-05-01 00:00:00+10:00' and E'2013-05-11 23:59:59+10:00' GROUP BY created::date, (created::date) ORDER BY "created_date" ASC
If I manually run that on my Postgresql database, it's all good, finds the following:
created_date total
2013-05-10 22
2013-05-11 1
However If I do the following:
for a in fads:
recent_ads.append({"dates": a['created_date'].strftime('%d/%m/%Y'), 'ads': a['total']})
It gives me the following output:
[{"dates": "09/05/2013", "ads": 1}, {"dates": "10/05/2013", "ads": 22}]
I'm at a loss at why it's changed the dates?
Anyone got any ideas?
Cheers,
Ben
Just a through on this. As of Django 1.4, Django now supports timezone aware dates and times. Perhaps it's possible that a conversion between your local timezone and the timezone that the data is stored in (possibly GMT) is taking place at some point. Perhaps that difference crosses the international date line, in which case the dates may show up differently.
Django has an interesting section describing the new timezone support feature.
https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/
That's what came to mind, anyway, when you described your problem. Hope this helps.
Python datetime from the standard python library is a mess.
Probably you are creating naive datetime instances (instances that lack timezone information).
# naive
now = datetime.datetime.now()
# TZ aware
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)
In recent Django, datetime storage is always offset-aware, so you better convert naive datetimes - otherwise an automatic (and sometimes wrong) conversion will take place.
Take a look at the docs about Django Time Zones.