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)
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 would like to provide a user with different default file names based on the wildcard that they select.
It seems that pyface.FileDialog inherits from HasTraits so I should be above to observe it's wildcard_index trait to notice the change and update the default_filename trait.
Here are my versions,
import pyface, traits, traitsui
pyface.__version__, traits.__version__, traitsui.__version__
('6.1.2', '5.1.2', '6.1.3')
EDM python environment
import sys
sys.version
'2.7.15 |Enthought, Inc. (x86_64)| (default, Jun 21 2018, 22:10:16) [MSC v.1500 64 bit (AMD64)]'
Using the WX backend
import wx
wx.version()
'3.0.2.0 msw (classic)'
Here is the simplest possible demo. of the problem,
from pyface.api import FileDialog
from traits.api import on_trait_change
class MyFileDialog(FileDialog):
""" Subclass that allows the suggested file name to change based on the wildcard type.
"""
#on_trait_change('wildcard_index')
def on_wildcard_changed(self, idx):
# This is never called
self.default_filename = [
'filename_john',
'filename_paul',
'filename_george',
'filename_ringo'][idx]
if __name__ == '__main__':
types = ["*.a", "*.b", "*.c", "*.d"]
dialog = MyFileDialog(
action="save as",
wildcard="|".join(["%s|%s" % (t, t) for t in types]),
)
dialog.open()
I suggest that you post this question to the ets-users google group (For viewers not familiar with it, this is at: https://groups.google.com/forum/#!forum/ets-users).
Fairly new to coding and have been browsing this site for a while, not clued up enough to give anything back yet though.
I'm trying to calculate the Hurst exponent using this code originally from QuantStart but modified to import data from Yahoo. Daily Hurst Exponent
When running in Powershell I return these errors:
C:\Program Files\Anaconda2\lib\site-packages\pandas\io\data.py:35: FutureWarning:
The pandas.io.data module is moved to a separate package (pandas-datareader) and will be removed from pandas in a future
version.
After installing the pandas-datareader package (https://github.com/pydata/pandas-datareader), you can change the import
from pandas.io import data, wb to from pandas_datareader import data, wb.
FutureWarning)
When changing from pandas.io import data, wb to from pandas_datareader import data, wb:
Traceback (most recent call last):
File "hurst.py", line 23, in
aapl = DataReader("AAPL", "yahoo", datetime(2012,1,1), datetime(2015,9,18))
NameError: name 'DataReader' is not defined
Please can someone help and guide me in what changes I'm missing to get the script to run properly.
Thanks,
James
from pandas_datareader.data import DataReader
...
ts1 = DataReader(symbol, "yahoo", start_date, end_date)
See the usage in the documentation
for pandas datareader:
from pandas_datareader import data
import datetime
start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
f = data.DataReader("F", 'yahoo', start, end)
I have a problem with dates in my system. I'm using CentOS6.
The problem is the following... I have differences in dates...
If I go to my Linux Console:
[andre#andre example]$ date
Tue Nov 22 23:57:10 WET 2011
If I go to Python Shell:
from datetime import datetime
datetime.now()
datetime.datetime(2011, 11, 22, 23, 50, 10, 146843)
And if I use a Template Tag from Django like this one:
{% now "jS F Y H:i" %}
I got this: 22nd November 2011 17:52
This is a 6 hour difference. Can you give me a clue on how to solve this?
Best Regards,
Most likely it's a mismatch between your Django TIME_ZONE setting and your server time zone. If you want Django to use your server's time zone, set TIME_ZONE = None