my datetime property is saving in mysql in this format 2011-03-17 00:00:00 but after fetchind the data with filter function it is giving March 17,2011 midnight but i have not say to do any this type of task. My question is how can i insist django to stic to show same value what is saved in MYSQL.
you'll want to use the datetime format, django's DateTimeField[1] really is a wrapper for datetime.datetime.
in the templates you can use the date[2] filter to apply the format you want for example:
{{ item.date|date:"Y-m-d H:i:s" }}
This should print out 2011-03-17 00:00:00 in the template. In views use datetimes.strftime[3]
[1] http://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield
[2] http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#date
[3] http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
I have a feeling your database schema knows this is a date, right? In that case it's not being stored in the format you describe, but as some representation such as seconds since the era.
This means that when you retreave it your code has to do something with it to make it look right. If you don't tell it how to look it'll default to the format you see, but if you use strftime in your python code and a filter in your templates you can make it look however you like, including the original format how you saw it.
Of course the easy way out is to store it in the db as text...
Related
After hours of searching, I found many posts that are related but wasn't able to help.
What I want to do is input eg: 10:30 AM into the TimeField.
In the django rest framework API on the browser, it is using this 10:30 AM format ('%I:%M %p').
But when I am using postman to test it, the output is in 24hr format ('%H:%M:%S'). I also tried to use 10:30 PM as input but the output I get is 10:30:00 instead of 22:30:00.
Many of the answers I found suggest to change the TimeField format in settings.py by using this line:
TIME_INPUT_FORMATS = ('%I:%M %p',)
but it doesn't work for me.
Sorry for my inexperience on django rest framework as I am still learning.
Here is the screenshot of the result.
On browser API:
On postman:
If you check the documentation on the TimeField you will see:
Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None)
Where
format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
So you either can specify the format and input_formats on the serializer, or set the settings.TIME_FORMAT and settings.TIME_INPUT_FORMATS.
Let's set the first case:
class MySerializer(serializers.Serializer):
...
birthTime=serializers.TimeField(format='%I:%M %p', input_formats='%I:%M %p')
Some suggestions:
Make your variable names snake case: birth_time.
You may need to play a bit around with the input format because you may expect many different inputs:
input_formats=['%I:%M %p','%H:%M',...]
Convert the result in Serializer validate method and return it.
import time
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )
I love the date tag that comes with Django.
Exceptionally, I'd like to format a DateTime object in my view (because I need to send a formated date string to an API, and not to display it in a Django template).
Do you know if there is a way to use this Django "system" outside templates?
In the mean time, I tried to use the strftime Python method but found out some con's:
It does not use the same format chars as Django, which makes my code deals with 2 different ways to handle date formatting.
By default, it doesn't care about the Django locales and writes English dates.
Thanks :)
The template tag is built on the Django formats utility libraries. See django.utils.formats.date_format for a named date format or django.utils.formats.dateformat.format for arbitrary ones. For example:
from datetime import datetime
# Date format string
from django.utils.formats import dateformat
formatted_date = dateformat.format(datetime.now(), "r")
# Named format
from django.utils.formats import date_format
formatted_date = date_format(datetime.now(), "SHORT_DATE_FORMAT")
I have the following URL definition:
url(r'^date-add/(?P<entity_id>\d+)$', views.date_add, name='date_add'),
That allows me to call date_add function with the following URL:
/app_name/date-add/<id>
I would like to fix this to allow a date. For example:
/app_name/date-add/1/2013-04-23
How should I edit my urls.py definition in order to achieve this?
You can define your URL regex like this:
url(r'^date-add/(?P<entity_id>\d+)/(?P<date>\d{4}-\d{2}-\d{2})/$', views.date_add, name='date_add'),
and the view, obviously would be
def date_add(request, entity_id, date):
#convert to datetime object from string here.
Typically you break it down into named parameters corresponding to the year, month and date:
url(r'^date-add/(?P<entity_id>\d+)/(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})/$', views.date_add, name='date_add_with_param'),
Then you can use datetime.date to construct the datetime in your view, which should receive year, month and day as parameters.
This is the usual pattern in particular for archive views, where the URLs might get more specific as you drill down - /archive/2013/ and /archive/2013/11/ might both be valid, although of course you probably wouldn't have a single regexp matching either. It might be unnecessarily complex compared to the single named pattern regexp karthikr's answer shows, which you could then parse with datetime.strptime.
In either case you can also use somewhat more restrictive regexps if you like, like ones that don't allow a first digit other than 0, 1, 2 or 3 for the month.
I'm currently using the timeuntil tag to show an items expiration date. It's currently spitting out...
{{rental_till|timeuntill}}
Which produces...
3 months, 1 week
Is it possible to get it to just show, the months, for example? Or any type of finer control over the output format, similar to the date tags.
To only show months, you could write a simple template filter that splits the string on the comma, and returns the first item of the resulting list. The filter code would look like this:
from django.template import Library
register = Library()
#register.filter
def split_timeuntil(duration):
return duration.split(",")[0]
Then in your template: {{rental_till|timeuntil|split_timeuntil}}
However, the timeuntil filter does not have the kind of formatting date has. You can easily create a custom filter that returns the format you want by copying the timeutil code in django/template/defaultfilters.py and django/utils/timesince.py.
No, timeuntil doesn't have any options, but you can simply create your own templatetag based on timeuntil and make it do whatever you like. See: https://code.djangoproject.com/browser/django/tags/releases/1.3/django/template/defaultfilters.py (line 729)
i want to display time in 12 hour format in django templates as iam storing time data in a charecter eg('18:30:00') field how to convert this string time data to date in django/python?
If you absolutely must do this, use time.strptime. It would be a better idea not to store structured data in a string if you can avoid it, though.
Within Django's templates you can use the date Template Filter:
{{ value|date:"h:i:s a" }} # '18:30:00' would appear as 6:30:00 p.m.
{{ value|date:"g:i:s a" }} # '18:30:00' would appear as 06:30:00 p.m.
value would be the string variable you pass in the Context to the Template when you render it. The string appearing after date: formats the time.
You can find more here: http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#date
Hank Gay's answer is more correct than mine; you should avoid keeping structured data in a string if at all possible.