I am trying to club together the data from google analytics and django application.
The datetime of django in database are in UTC. Google analytics data has timezone as IST.
I am getting data from google analytics for a period based on IST and getting data from django for same period in IST. There are lot of variations .
Is there any way this can be solved ?
IST (Indian Standard Time) is 5:30 ahead of UTC (http://www.timeanddate.com/time/zones/ist). When getting data from Django, make sure that you use localized datetime objects:
import pytz
from datetime import datetime
tz_india = pytz.timezone('Asia/Kolkata')
start = tz_india.localize(datetime(#Here create you datetime object from IST))
end = tz_india.localize(datetime(#Here create you datetime object from IST))
Your best option here could be to change the default timezone from your Django App to IST.
First of all you should check Django settings: TIME_ZONE
You will understand better how to fix it if you understand how it works.
To change the default timezone to IST you need to add in your settings.py:
TIME_ZONE = 'Asia/Kolkata'
If Asia/Kolkata doesn't fit your needs, you can check all the available time zones in the next URL:
List of Time Zones
If you prefer to manage the datetime objects and convert from UTC to IST or viceversa you can do it like this:
Convert data from UTC to IST
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(format)
Output: 2015-05-18 10:02:47 UTC+0000
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print now_asia.strftime(format)
Output: 2015-05-18 15:32:47 IST+0530
Convert data from IST to UTC
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in Asia/Kolkata
now_asia = datetime.now(timezone('Asia/Kolkata'))
print now_asia.strftime(format)
Output: 2015-05-18 15:32:47 IST+0530
# Convert to UTC time zone
now_utc = now_utc.astimezone(timezone('UTC'))
print now_utc.strftime(format)
Output: 2015-05-18 10:02:47 UTC+0000
Related
In my postgresql db my datetime are stored as the following format:
>>> p.publish
datetime.datetime(2020, 12, 6, 6, 19, 36, 269492, tzinfo=<UTC>)
now I want to display times locally using
{% load tz %}
{{ post.publish|localtime }}
nothing happens.
Then I tried to do it in the shell:
from tzlocal import get_localzone
local_timezone = get_localzone()
pytz.utc.localize(p.publish,is_dst=None).astimezone(local_timezone)
which gives me the following error:
ValueError: Not naive datetime (tzinfo is already set)
so my question is why it cannot convert timedate when tzinfo is already set, and how to get around it. Is it not the whole point to store data in data base with a certain timezone(here UTC) and then display it in different time zones when required? am I missing something here?
If the tzinfo is already set, you can replace it with the one you wanted to set.
For example:
import pytz
utc = pytz.UTC
_today_date.replace(tzinfo=utc)
Here, _todate_date is datetime object.
Hi i am creating ics file for calendar invitation, as far as i see that if i dont put time zone some emails may become conflict, i have checked working ics files from zoom and i see that they put
BEGIN:VTIMEZONE
TZID:Turkey Standard Time
BEGIN:STANDARD
DTSTART:16010101T000000
TZOFFSETFROM:+0300
TZOFFSETTO:+0300
END:STANDARD
END:VTIMEZONE
now i translated this to code like
timezone = Timezone()
timezone.add('TZID','Turkey Standard Time')
timezoneStandard = TimezoneStandard()
timezoneStandard.add('TZOFFSETFROM', timedelta(hours=3))
timezoneStandard.add('TZOFFSETTO', timedelta(hours=3))
timezoneStandard.add('DTSTART','16010101T000000') <==== PROBLEM IS HERE
timezone.add_component(timezoneStandard)
cal.add_component(timezone)
But i dont know to translate 16010101T000000 , i am getting error You must use datetime, date, timedelta
This is ISO-8601, you can parse this for example with .isoparse [readthedocs] from the dateutil package [readthedocs].
You can install this, for example in your local environment with:
pip3 install dateutils
Then you can parse this with:
>>> from dateutil.parser import isoparse
>>> isoparse('16010101T000000')
datetime.datetime(1601, 1, 1, 0, 0)
So you can use this in your code with:
timezoneStandard.add('DTSTART', isoparse('16010101T000000'))
I'm using TestCase.client to test my views. And when I call timezone.now() from test case, i get 2015-11-17 07:48:26.826661+00:00, but when I call
start = timezone.make_aware(datetime.strptime(
date_text + ' ' + time,
'%y/%m/%d %H:%M'
))
from view I get 2015-11-17 07:36:00+02:00.
How to make them use the same timezone?
I'm running using ./manage.py test --settings=www.tests_settings and www/tests_settings.py contains following:
from .settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
USE_TZ = True
TIME_ZONE = 'Europe/Kiev'
>>> django.__version__
'1.8.4'
>>> pytz.__version__
'2015.7'
>>> sys.version
'3.4.3 (default, Mar 26 2015, 22:03:40) \n[GCC 4.9.2]'
Oh, I see. make_aware returns time in default time zone, and now - in UTC. And to get local current time, I need to do timezone.localtime(timezone.now()).
But documentation recommends to deal with time and timezones like with text and encodings - store everything in UTC (unicode) and convert only when receiving or giving it to user.
i have wrote a simple script to get inputs from user and store it in the database.
I also want date input but some problems are arising.
First I have used datetime.date() function and passing the date but it is throwing some error.
I don't understand why?
import pyodbc
import datetime
class data:
def __init__(self):
self.name=raw_input( "Enter Name: ")
self.section=raw_input( "Enter section: ")
self.eon=datetime.date(1943,3, 13) # This is in the requested 'YYYY-MM-DD' format.
a=data()
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=KIRAN-PC;DATABASE=testing')
cursor = cnxn.cursor()
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,?)",(a.name,a.section,a.eon))
cnxn.commit()
Error:
Enter Name: Tim
Enter section: A
Traceback (most recent call last):
File "C:/Python33/data2.py", line 15, in <module>
cursor.execute("Insert into Students (Name,Section,Enrol_On) Values (?,?,?)",(a.name,a.section,a.eon))
Error: ('HYC00', '[HYC00] [Microsoft][ODBC SQL Server Driver]Optional feature not implemented (0) (SQLBindParameter)')
Change the import from from datetime import datetime to import datetime. With your current code you import the class datetime from the module datetime and call the date method from this class with wrong parameters. But you want to call the constructor of the date class in the datetime module.
Update to answer your edit
According to https://code.google.com/p/pyodbc/issues/detail?id=204:
On Windows, you need to use DRIVER={SQL Server Native Client 10.0} for a driver that understands the ODBC date type.
Your current driver SQL Server does not understand how to pass the date datatype to your database.
You also have to pay attention that in your database the column Enrol_On is of type SQL_TYPE_DATE. See https://code.google.com/p/pyodbc/wiki/DataTypes for the mapping of python datatypes to SQL types.
Okay simple question (I think).
I have a DateTime field (auto_add_now) and when output to a template
{{ edited|date:"DATETIME_FORMAT" }}
I get the expected result of "Sept. 16, 2012, 12:01 p.m."
But unfortunately things are slightly more complicated since I am using Backbone.js and need to pass the datetime with JSON, and since it is only used for display purposes I decided to pass it as a nice locale formatted string. So I dug into the code and found what the template tag uses and this is what I setup.
from django.utils.formats import date_format
return {
'created': date_format(self.created, 'DATETIME_FORMAT'),
}
But that ends up with this "Sept. 16, 2012, 5:01 p.m."
I have a feeling it has to do with the following on the template tag
#register.filter(expects_localtime=True, is_safe=False)
I also tried this but ended up with the same results
from django.utils import timezone
tz = timezone.get_current_timezone()
logger.info(tz)
logger.info(self.edited)
logger.info(format(self.edited, 'DATETIME_FORMAT'))
logger.info(self.edited.replace(tzinfo=tz))
logger.info(format(self.edited.replace(tzinfo=tz), 'DATETIME_FORMAT'))
Which gave me this
INFO: America/Chicago
INFO: 2012-09-16 17:01:52.921276+00:00
INFO: Sept. 16, 2012, 5:01 p.m.
INFO: 2012-09-16 17:01:52.921276-06:00
INFO: Sept. 16, 2012, 5:01 p.m.
So yeah, I must be missing something, and I have been up and down the django documentation and cannot find anything that could point me to what I am doing wrong. Thanks for any help.
I figured it out. And sadly it was in the Django Timezones documentation that I thought I had exhausted. Localize Usage timezone.localtime()
from django.utils.formats import date_format
from django.utils import timezone
date_format(timezone.localtime(page.created), 'DATETIME_FORMAT')
Maybe the following will help you.
>>> obj = MyModel.objects.get(...)
>>> data = {"date_format": obj.edited}
>>> from django.core.serializers.json import DjangoJSONEncoder
>>> data = json.dumps(data, cls=DjangoJSONEncoder)
>>> data
'{"date_format": "2012-09-16T21:45:46Z"}'
Send the json formatted data from your view:
E.g return HttpResponse(data, mimetype='application/json').
And then at your client side code you can convert the date_format to the local timezone with:
(Assuming response is the JSON parsed object)
var d = new Date(Date.parse(response.date_format));
// Sun Sep 16 2012 22:45:46 GMT+0100 (BST)