I am reading a Facebook updates feed using the python library 'feedparser'.
I loop through the collection of entries in my Django templates, and display the results.
The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:55:52 +0000
How can I...
A) Use a Django filter to clean the date time in the for loop on the template.
...or...
B) Parse the date and format the updated date in the view, esentially cleaning the date in the collection of entries before it is iterated over in the view.
NOTE: I have tried both approaches. Django's date filter does't recognize it, and the iso8601 library I tried to parse the string didn't either.
Anybody have any experience with this? Thanks for your help!
UPDATE:
Using the updated_parsed value from feedparser in a Django template didn't work so well. But a Django snippet of a filter for this very thing already exists!**
Django Snippet: http://www.djangosnippets.org/snippets/1595/
Use entries[i].updated_parsed instead of entries[i].updated, and feedparser will return a parsed 9-tuple for you. (Documentation)
Then build a datetime object and pass it to Django or format to a string by yourself.
There is a similar question here.
This worked but wasn't what my final solution ended up becoming.
This solution iterates over the feed entries collection I get back from Facebook. I then parse the datetime and set the updated property to that new datetime. (Also, ignoring the +0000)
for entry in feed.entries:
entry.updated = datetime.strptime(entry.updated, "%a, %d %b %Y %H:%M:%S +0000")
The entries collection is returned to the template which I can now use the Django 'date' filter to format the date.
Related
I have start_date of DateField() which is in utc.I want to convert it to timezone aware object
I tried writing
{{ start_date|timezone:'Asia/Calcutta' }}
It displays nothing.Is timezone only for DateTimeField()?How can I use it on DateField().
Yes, unfortunately, this only works for datetime objects (s. https://github.com/django/django/blob/abaf0ab4a444977dc8ac07b9b63256814c352245/django/templatetags/tz.py#L46)
As far as I know, there's no real way to make a date object timezone-aware. You can convert a date object to datetime though (s. https://stackoverflow.com/a/1937636/246028)
If you tell us what you're trying to achieve by making a date timezone-aware, I can try to amend my answer.
I want to save date in my django model into desired format.
post_date = str(request.POST['date'])
I am getting date from front end is 12/21/2016
i want to save this date in my django modal is like 21-Dec-2016.
How can i do it.
it will be good if you can provide some sample code.
Thanks in advance.
you want to store in DB string parameter? The easiest way convert input string to date and then convert from date to string. But of course it is more logical to store date format imho
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.
I am making a blog and store the publishing date of a blog post in the datastore. It looks like this:
post.date = datetime.datetime.now()
It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can I set that how the date is displayed? I'd like to set the date format like in UNIX date function (like %Y/%m etc). I tried to add some parameters in my templates but that returned errors.
Thanks in advance!
-skazhy
I think strftime is the method you're looking for.
From the link:
>>> d.strftime("%d/%m/%y")
'11/03/02'
If you pass in the result of the strftime in your 'template_values' or similar (the dictionary you use to pass parameters to the template) instead of the actual date it will be displayed instead.
You can use .strftime() on a datetime object to do the formatting. See the relevant python documentation for details.
I need to parse a date/time string from user input, and convert to UTC based on timzeone info not available in the string for datetime.strptime() (any suggestions?). Is there a straightforward way of doing this?
Ideally, on google app engine i'd like to grab local time with tzinfo from the browser if possible also.
timezone_string = "GMT-0800"
fields = ("eventstartmonth","eventstartday", "eventstartyear", "eventstarttimehour", "eventstarttimeampm")
date_string = '_'.join(map(lambda x: self.request.get(x), fields))
# date_string = "01_11_2000_1:35_PM"
dt = datetime.datetime.strptime(date_string, "%m_%d_%Y_%I:%M_%p")
# how to convert dt into a tz-aware datetime, and then to UTC
While searching for similar information I came across a demo app engine app (with source included) that demonstrates how to convert timezones in a way that's similar to what you've requested. Unfortunately, though, you'll need to create custom tzinfo classes (explanation/code in the demo app linked above) for each timezone you'll be converting.
If you need to be able to handle any timezone and/or want to take the easy route, I'd recommend using the pytz module. However, keep in mind, pytz is a rather bulky module that you'd have to upload to your GAE instance.