set input to AM PM in django timefield - django

i want to allow users to be able to choose between am and pm with my django timefield
Currently if I enter:
11:00 AM
, i get a form error: "Enter a valid time."
If I enter:
11:00
the form validates with no problem.
I also tried:
class RemindersForm(forms.ModelForm):
remdinder = forms.TimeField(input_formats='%H:%M %p',)
class Meta:
model = NotificationPreference
fields = (
'reminder',
)
This changes the input format to:
11:00:00
and still gives me the above validation error.
What am I doing wrong?

I was searching for a similar answer and I didn't find a suitable one for models.TimeField, so, the easiest solution that I found for doing this site wide would be to setting in your settings.py the following global variable:
TIME_INPUT_FORMATS = ['%I:%M %p',]
I hope this helps someone.
To use other formats see:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

To get a 12hr time format you would use the following:
For input (This is the list of formats Django uses in validation):
field = TimeField(input_formats=('%I:%M %p',...,...))
For output (This is the format Django will use to display time values):
field = TimeField(widget=TimeInput(format='%I:%M %p'))
The %I indicates a 12 hour clock format whereas the %H indicates a 24 hour clock format.
Additionally, the default list of input_formats can be found in each locales formats.py file. Django uses the first format in the input_formats list as the default output format for time fields.

I think you can do some thing like this in forms.py
field = DateTimeField(input_formats='%H:%M %p',...)

According to the Django documentation, and python's datetime docs, it should work if you change the time input settings to:
TIME_INPUT_FORMATS = ('%I:%M %p',)

Related

How to convert django default timezone to different format

Time format
"2018-12-13T05:20:06.427Z"
django providing time zone in above format when i am fetching data from database using ORM query.
In my model field is in below way.
models.DateTimeField(auto_now=True, blank=True,null=True)
How can i convert it into "24 feb 2018" like this
Apart from #Sosthenes Kwame Boame answer, you can use strftime for formatting.
import datetime
time = datetime.datetime.now().strftime('%d %b %Y')
Out[13]: '13 Dec 2018'
Instead of passing datetime module to time variable, you should pass your model field's value.
If you want to learn more about format type then you can visit the documentation page.
I am guessing you want to display this on the frontend?
You need to do this in your template:
{{ object_name.datefield_name|date:'j b Y' }}
So you call the datefield and render it with the '|date' tag with a format assigned ':'FORMAT''.
Learn more about the date tag, along with the various formats here: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#date

Parse european string date to Django DateField

I am using USE_L10N = True in my app settings. As I understood, this setting let Django adapt date format according to the user current locale.
So in the admin, my model that contains a DateField is correctly represented in the form with the format "%d/%m/%Y".
The problem I have is when I want to create a new object from my code. I have a CSVParse custom function parsing a CSVĀ file and creating objects. One of the column in the CSV has the same format as above ("17/12/2015" for instance). I tried to parse the date with the line below but it returns "None". In the documentation of date_parse, I can see that it means a wrong format.
from django.utils import dateparse
date_csv = "18/12/2014"
date = dateparse.parse_date(date_csv)
What am I missing?
Thanks
Django dateparse uses date_re (regex) for parse_date and date_re format is year-month-day
date_re = re.compile(
r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
)
The input you are giving is having format day/month/year hence you are getting None as result.
Check out strptime
import time
date_csv = "18/12/2014"
date = time.strptime(date_csv, "%d/%m/%Y")

Django ReportLab Timezone

I'm using ReportLab in Django. I have a model with the following field:
time_stamp = models.DateTimeField(auto_now_add=True)
And my TIME_ZONE variable in settings.py is set to:
Africa/Johannesburg
I use a formset to populate this model. The time_stamp field saves correctly with the correct time zone, but when I place the time_stamp in my ReportLab pdf, the time zone is set to UTC.
For example:
time_stamp in the saved model (as str(time_stamp)[:19] is:
2015-03-04 07:57:28
But time_stamp in pdf document (as str(time_stamp)[:19] is:
2015-03-04 05:57:28
Exactly 2 hours earlier (Africa/Johannesburg is UTC + 2hours).
How can I set the time zone for ReportLab? Should it be specified in settings.py or in views.py while generating the pdf? If there is no solution, how do I add 2 hours to the time_stamp?
Some answers suggested changing auto_now_add=True with default=datetime.datetime.now(), but this creates a warning while migrating the database (Naive expression used).
I'm not a user of Reportlab but in general I don't think setting USE_TZ=False is the right approach to solve your problem. Set it back to True and instead of truncating your time stamp yourself like:
str(time_stamp)[:19]
You should try applying Django's date template filter in your template, e.g.:
{{ time_stamp|date:"SHORT_DATETIME_FORMAT" }}
It can be confusing how Django is handling timezones. But it's best practice to save timestamps in your database in UTC. You may want to refer to Django's timezone FAQ:
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#time-zones-faq

Django Model DatetimeField without seconds

I want to enter date and time in my admin site with
date = models.DateTimeField()
But I dont want to have the seconds in my view. Is it possible to display the time like this:
10:45 instead of 10:45:00 ?
Yes you can:
https://docs.djangoproject.com/en/dev/ref/forms/fields/#datetimefield
input_formats
A list of formats used to attempt to convert a string to a valid datetime.datetime object.
If no input_formats argument is provided, the default input formats are:
Thats if you want to save as well with no seconds, If you only want to change how its displayed in your templates your can use the date template filter:
https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#date

unixtimestamp input in DataTimeField

Per specification I have date and time input in UnixTimeStamp Also, I need check that I have only digits on input (nor something like this "2011-12-12")
I have forms.DataTimeField and model.DataTimeField now.
I decided to modify this in such way:
Added UnixTimeStampField(forms.RegexField) - here I check with regular expression, that I have only digits.
But I got problem with model, since UnixTimeStampField(forms.RegexField) is based on string and need to be converted to datatime.
I don't like this solution.
How I can create something like UnixTimeStampField(forms.DateTimeField)?
I tried to do this, but then I have "123321" on input I got "Incorrect parameter" from DateTimeField validators.
You don't need a custom model and/or form field for this. Just use the built-in forms.DateTimeField and models.DateTimeField, then add the following settings to your settings.py:
DATETIME_FORMAT = "U"
DATETIME_INPUT_FORMATS = ("%s",)
Read more about this settings here.