Parse european string date to Django DateField - django

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")

Related

DateTimeField to str and read from str

I have a problem with understating how to deal DateTimeField.
I have model with DateTimeField, view which returns jsons containing this field and another view which use provided data (as string) to filter result
# model
date = models.DateTimeField(auto_now=True)
# first view
return str((self.date.isoformat() for date in ...))
# f. exp: ['2019-11-19T15:22:47.788254+00:00']
# second view
Row.objects.filter(data__lte=data_from_GET)
If I have used 2019-11-19T15:22:47.788254+00:00 I reciver error
ValidationError at /csv/
["'2019-11-19T15:22:47.788254+00:00' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
I can not find an easy way (without string manipulation) to return data in a format acceptable by the filter method.
What is interesting:
2019-11-19T15:22:47.788254-00:00 not ok
2019-11-19 15:22:47.788254+00:00 not ok
2019-11-19 15:22:47.788254-00:00 ok
You could use EpochUTC and integer values to compare different dates. If you need to display these dates you can transform them into strings using the new Date constructor.

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

Date exported is displayed as UTC

I'm trying to export some data from Django to Excel using openpyxl.
The exported datetimes are correctly interpreted as such in Excel, but their printout is in UTC, not in local timezone (CET in this case) as I'd expect.
I tried to use to_excel, but that only outputs datetimes converted to excel's internal float format. Which is in addition also interpreted as float, not datetime. When formatted as datetime, it's still in UTC
I also tried to use Django's django.utils.timezone.localtime, but again the dates are rendered in UTC.
I could just subtract the timezone offset from my dates, but I feel it's more likely I'm missing something here.
How can I export datetime data such that Excel would display it in my local timezone?
I had the similar problem and solved it in the following way.
May be it helps.
from dateutil.tz import tzutc, tzlocal
TZ_UTC = tzutc() # UTC timezone
TZ_LOCAL = tzlocal() # Local timezone
datevalue = value #value I get from API I am using, which is datetime object.
# For some reason I don't get tzinfo filled).
datevalue = datevalue.replace(tzinfo=TZ_UTC) # Adding time zone info for UTC
datevalue = datevalue.astimezone(TZ_LOCAL) # Converting to local timezone
datevalue = datevalue.replace(tzinfo=None) # Removing tzinfo to correctly record local time to Excel
cell.value = datevalue
Excel itself has no concept of timezones and will always dates and times naively. In this context the only sane thing to do is to convert to UTC which is what openpyxl does. openpyxl.utils.datetime is the module to look at if you want to change this
I ended up using a combination of javascript & server-side processing:
At the client HTML I create an input for user's local timezone:
<input type="hidden" value="" name="tz" id="xls-tz"/>
and populate its value (using jQuery):
$("#xls-tz").val(new Date().getTimezoneOffset());
At the server, I parse the timezone offset & write to openpyxl accordingly:
tz_offs = int(request.GET.get("tz", "0"))
ws.cell(row=row, column=2, value=item.time - timedelta(minutes=tz_offs))
That comes IMO pretty close to what I needed.
Thanks Charlie for the hint about Excel not being TZ aware.

Django template tag, python timezone aware dates different results

I have :
TIME_ZONE = 'Europe/Paris'
USE_L10N = True
USE_TZ = True
in my settings.py file. I am living in Istanbul/Turkey and there is one hour difference between Paris and Istanbul.
In the admin side when selecting a date, django correctly shows 1 hour difference. And using template tag i am getting the datetime i have set in the admin.
But when i pass the datetime via python using beginning_date.strftime("%H:%M") python substracts 1 hour from the value that was set via admin which is not true.
How can i solve this?
Use the Django template defaultfilters to format your dates in Python code.
from django.template.defaultfilters import date as _date
_date(datetime_object, "%H:%M")
And, maybe related: Django cannot reliably use alternate time zones in a Windows. See documentation.
I don't think Turkey has anything to do with it.
My guess is that the one-hour difference you're seeing is between the Paris timezone—which is being used, by default, to interpret and display dates—and UTC—which is being used to store the datetime, and which is the timezone of the datetime returned from the database.
If that's correct, then you can just use django.utils.timezone.localtime to convert the datetime to the current time zone (which by default will be TIME_ZONE):
localtime(beginning_date).strftime("%H:%M")

set input to AM PM in django timefield

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',)