Application built with: Python and Angular
I have a form that uses the following input to allow a user to insert a date:
<input type="datetime-local" id="clubJoined" name="clubJoined" class="date-input" formControlName="clubJoined">
And in my python backend I convert this string object into a date object using the following:
# - Club Joined
"club_joined": datetime.datetime.strptime(request.form["clubJoined"], '%y-%m-%d %H:%M')
But this gives me a formatting error:
ValueError: time data '2011-01-01T23:36' does not match format '%y-%m-%d %H:%M'
So I added the T so that the conversation format looks like this:
# - Club Joined
"club_joined": datetime.datetime.strptime(request.form["clubJoined"], '%y-%m-%dT%H:%M')
But this gave me the following error:
ValueError: time data '2011-01-01T23:36' does not match format '%y-%m-%dT%H:%M'
How do I format this correctly?
The correct format is "%Y-%m-%dT%H:%M"
%y stands for two-digits year, here you can find full list of format options.
Related
I'm new to python, and have little experience using try & except statements.
My code needs to check the date format entered by user. I'm currently using the code from this thread:
How do I validate a date string format in python?
but it's not working properly:
i.e. the following do not raise an exception, where date_text = "20189901", as does date_text = "20181301"
import datetime
date_text = "20189901"
try:
datetime.datetime.strptime(date_text, '%Y%m%d')
except ValueError:
raise ValueError("Incorrect data format, should be YYYYMMDD")
Is there a way to check date format using a simple if statement?
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")
Is there any way, how to parse line which contains date in some format and value? I'm looking for general solution. I'm writing script, which should validate string. My input is some string and time format. For example:
in first file and known time format
[10:17:21 20.04.1911] 890.584
[%H:%M:%S %d.%m.%Y]
in second file and known time format
10:17:21-20.04.1911 890.584
%H:%M:%S-%d.%m.%Y
in third file and known time format
(20-04-1911) 890.584
(%d-%m-%Y)
in fourth file and known time format
20-04-1911 10:17:21 890.584
%d-%m-%Y %H:%M:%S
etc.
I already have function to get timestamp from date according to time format, but I don't know, how to parse date from that line.
Any ideas? Thanks.
I would use try here:
import datetime
def parse_date(line):
for template, length in [("[%H:%M:%S %d.%m.%Y]", 21),
("%H:%M:%S-%d.%m.%Y", 19), ...]:
try:
return datetime.datetime.strptime(line[:length], template)
except ValueError:
pass
This will work through all the templates, return a datetime object if it can extract one from the line and return None if none of the templates match.
In my form I have a DateField called booking_date that is rendered with the AdminDateWidget. The contents of the booking_date field needs to be internationalized. The problem appears when I want to use the value of the field in something like this:
booking = Booking.objects.get(booking_number='BN34D', booking_date='2010-11-21')
But if my date format is '%d.%m.%Y':
booking = Booking.objects.get(booking_number='BN34D', booking_date='21.11.2010')
I get a 'ValidationError: Enter a valid date in YYYY-MM-DD format'
How can I make the query regardless of the date format used?
You should parse it first with a localized version of the strftime format.
from datetime import datetime
d = datetime.strptime('...')
booking.objects.get(..., booking_date=d.date())
Use these formats in strptime:
http://linux.die.net/man/3/strftime
You shouldn't rely on passing directly from the user into the query.
Looks like you should be doing the following from your specific example:
d = datetime.strptime('%d.%m.%Y')
booking = Booking.objects.get(booking_nmber='BN34D', booking_date=d)
As I understand your question, you don't know for sure in advance, which locale will be used. That can bring you into unsolvable problems. ("10-11-12" could be Oct 11, 2012 or Nov 12, 2010 or ...)
So you must have a limited, distinguishable set of possible formats. Then you can do:
POSSIBLE_FORMATS = ('%d.%m.%Y', '%Y-%m-%d', '...')
for f in POSSIBLE_FORMATS:
try:
d = datetime.date.strptime(date_str, f)
break
except ValueError:
continue
raise ValueError
booking = Booking.objects.get(booking_number='BN34D', booking_date=d)
I have solved the problem using this:
from django.utils import formats
formats.get_format('DATE_INPUT_FORMATS')[0]
This format is then used for parsing the date like xyld showed.