Maintaining microsecond accuracy when transferring datetime values between Django and JavaScript

It appears that django, or the sqlite database, is saving datetimes with microsecond precision. However, when it comes to transferring a time to javascript, the Date object only works with milliseconds:

var stringFromDjango = "2015-08-01 01:24:58.520124+10:00";
var time = new Date(stringFromDjango);
$('#time_field').val(time.toISOString()); //"2015-07-31T15:24:58.520Z"

Notice how the 58.520124 becomes 58.520.

This poses an issue when, for instance, I need to create a queryset for all items with a datetime before or at the time of an existing item (such as

MyModel.objects.filter(time__lte=javascript_datetime)
). Since the microseconds are truncated, the item does not show up in the list due to the inequality.

Is there a way to address this problem? Is there a javascript datetime object that handles microsecond accuracy? Can I convert times in the database to milliseconds (especially as I use auto_now_add frequently) or request the query be done with reduced precision?

Answer №1

What are some ways to address this issue?

In order to store less precision, you can try the following methods:

  • Attempt to configure your database platform to only store milliseconds and disregard any extra precision (which may be challenging with SQLite)
  • Ensure that you insert values with the desired precision every time (although it might be difficult to cover all scenarios)

Is there a Javascript datetime object that allows for microsecond accuracy?

If you encode your dates as Strings or Numbers, you have the ability to include as much accuracy as needed. There are alternative options available (some of which are discussed in this thread). However, if extreme accuracy is not necessary, pursuing this approach may not be the most practical.

Can times in the database be truncated to milliseconds?

Yes, but since you are using SQLite, the process can be somewhat unconventional. SQLite does not truly have date types; rather, values are stored in fields designated as either text, real, or integer. The underlying storage classes determine the precision and range of the values that can be stored. Additional information on these differences can be found here.

For example, switching the underlying storage class to integer could result in truncating dates stored within that field to a precision of 1 second. When executing queries from JavaScript, you could also truncate your dates utilizing the Date.prototype.setMilliseconds() function. For instance..

MyModel.objects.filter(time__lte = javascript_datetime.setMilliseconds(0))

A more advanced DB platform would provide better handling in this scenario. In PostgreSQL, for instance, you can specify the exact precision at which timestamps are stored, down to milliseconds (matching that of JavaScript)..

alter table "my_table" add "my_timestamp" timestamp (3) with time zone

MySQL also offers similar capabilities, allowing you to specify precision.

.. or request reduced accuracy in queries?

Although possible, this approach is typically not advised.

If the filtering criteria being used is too precise, then truncation can be applied before filtering (as shown in the ..setMilliseconds() example above). However, if the values stored in the database that are being compared against are overly precise, complications may arise.

You might attempt to format or truncate the stored values to decrease their precision before comparison with your criteria, yet this operation must be performed for each value stored. Considering this could involve millions of values, any indexes created for the stored values may become ineffective due to dynamically generated values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send location data to the PHP server through AJAX and then fetch it in JavaScript once it has been handled

I am looking to transfer coordinates from client-side JavaScript to server-side PHP using Ajax, and then retrieve the processed result back to JavaScript for further use. While I have managed to pass the data to PHP successfully, I am struggling to figure ...

Restrict the number of labels on Chart.js exclusively for smaller displays

How to Limit the Number of Labels on a Chart.js Line Chart I am looking for a way to decrease the number of labels on my line chart only when it is viewed on a small device. The solution provided in the previous post suggests using the following code: xAx ...

What could be the reason for the lack of rerendering in this child component?

Currently, I'm delving into ReactJS and attempting to grasp how child component rendering functions. To illustrate, consider the following example: var externalCounterVar = 10 class Counter extends React.Component { constructor(props){ super(pr ...

Manipulating Q objects by dynamically introducing new conditions

My Q object setup looks like this: params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword) Filtering my model based on this configuration works well. Model.objects.filter(params) However, my goal is to ...

When a panorama is entered in ThreeJS/Panolens, what is the orientation of the camera?

I want to use an equirectangular image with Panolens and achieve the same panorama viewer effect as seen in the links below: Even though Panolens.js is based on Three.js, I encounter a different result when I input my image compared to the first link abov ...

Having trouble receiving RSS updates through my Django webhook setup. The replay feature is sending blank POST and GET data

Trying to set up webhooks for Django with the use of Superfeedr.com to receive webhooks. Testing is being done using the RSS feed link provided by them: . Realtime website updates can be made to test the webhook functionality. However, upon updating the w ...

Is it possible to implement cross-domain login with Passport.js?

Is it possible for a user to log in from a different domain? For example, the main site has a login form that uses AJAX to post to a route on my Node.js server. // Submit form to Node server FROM WEBSITE $('#submit-project-form').submit(function ...

How can I customize the styling of an SVG pseudo element using Font Awesome 5?

I've implemented font awesome 5 pseudo elements to attach an :after tag to my element as shown below: &:after { content: "\f068"; font-weight:400; color:$brandRed; float:right; font-family: "Font Awesome 5 Pro"; } The c ...

What is the best way to store objects containing extensive binary data along with additional values?

I'm currently working on saving a JavaScript object that includes binary data along with other values. I want the output to resemble the following: { "value":"xyz", "file1":"[FileContent]", "file2&quo ...

Store the checkbox's data in the database for safekeeping

Hey there, I'm working on saving the value of a checkbox using PHP. The twist is that the value is generated through JavaScript. How can I handle this scenario and save the value using PHP? Checkbox: <input type='checkbox' name='ca ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

Redux saga will halt all other effects if one fails during execution

Having some trouble with yield all in saga effect, I've included a snippet of my code below function* fetchData(item) { try { const data = yield call(request, url); yield put(fetchDataSuccess(data)); } catch (error) { yield put(fetchDa ...

Utilizing JavaScript's Array.sort() method for sorting objects with varying properties

Currently, I am dealing with these specific Objects: let obj1 = { from: Date, to: Date } let obj2 = { date: Date } These Objects have been placed in an Array: let arr = [ obj1, obj2 ] My goal is to organize the objects within the array by using arr.sort( ...

Looping through data returned from Ajax call and displaying it as HTML in CodeIgniter using JQuery

Just dipping my toes into the world of JQuery AJAX, here's what I've got so far: $(document).ready(function() { $("#city").change(function() { var city_id = $("#city").val(); if (city_id != '') { $.ajax({ type ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

Repeating every other item in a list using ng-repeat in AngularJS

Using AngularJS version 1.5.3 In my view, I have a list of items that I want to display. After every two items, I would like to show a new div below the first one. <div class="col text-center" ng-repeat="event in weekDay.events"> &nbsp;& ...

An error message stating "ReferenceError: str is not defined" was encountered in Firefox while using the Gettext Library

The gettext.js library seems to be giving me trouble. When I try to run the "index.html" file, an error message saying "ReferenceError: str is not defined" pops up. this.LCmessages[lang] = new jsGettext.Parse(str); I'm not sure where the str variabl ...

Implementing a Fixed Position for a Single Record in Extjs 4.2 Sortable Grid

Is there a way to allow users to sort by any column in a simple grid with sorting enabled, while ensuring that a specific record is always displayed at the last position (based on its ID)? I am working with ExtJS 4.2.2. ...

Having trouble with a single GET request not functioning properly on Safari due to an Authorization issue in Angular 6

I've encountered this issue in several locations, yet haven't found a clear solution. Only one GET request is showing as unauthorized (401), but when I check the debugger, everything seems to be fine and all other requests are functioning properl ...

Top Recommendation for Embedding Individual Text Passages in Django (outside of database)

Although I'm not a developer, I have been working on small Django projects for my business for quite some time now. I am currently contemplating the best way to incorporate longer text passages such as directions, privacy policies, or business hours ...