How can I programmatically alter a view query? I need to be able to pass a date+time argument to a view. When I add a date field as a contextual argument, the query is only passing this in Y-m-d format. I need to include the time so that I can get a list of events that are happening at a certain time.

I think I should be able to use views_query_alter to change the ->where condition, but I'm not sure where to go from there. If I do this:

function mymodule_views_query_alter($view, $query) {
  if ($view-&gt;current_display == 'mydisplay') {
    dsm($query-&gt;where[0]['conditions'][0]['field']);
    $query-&gt;where[0]['conditions'][0]['field'] = ???
  }
}


This is the output from the dsm:

DATE_FORMAT(node__field_session_date.field_session_date_value, '%Y-%m-%d') = :node__field_session_date_field_session_date_value


How do I change that %Y-%m-%d to include the time in the correct format?
I would approach this from a different angle. You can create a new Datetime argument type (a views plugin) and then add an association for your desired field to your new argument. This means we aren't modifying a query in an unpredictable way, and you can see in configuration that the argument is different. You can set this up to use any date format you wish, but keep in mind that time zones may affect the values.

First, we'll create the new argument type. We're extending the existing base Date argument and only changing the date format. The @ViewsArgument value will need to match the argument id value in the field assignment later on.

mymodule/src/Plugin/views/argument/FullDatetime.php:

&lt;?php

namespace Drupal\mymodule\Plugin\views\argument;

use Drupal\datetime\Plugin\views\argument\Date;

/**
 * Argument handler for a full datetime (CCYYMMDD-HHMM).
 *
 * @ViewsArgument("mymodule_full_datetime")
 */
class FullDatetime extends Date {

  /**
   * {@inheritdoc}
   */
  protected $argFormat = 'Ymd-Hi';

}


And now we'll create a new argument assignment for the Session Date field.

mymodule/mymodule.module:

/**
 * Implements hook_views_data_alter().
 *
 * @param array $data
 */
function mymodule_views_data_alter(array &amp;$data) {
  $data['node__field_session_date']['field_session_date_full_datetime'] = array(
    'argument' =&gt; array(
      'field' =&gt; 'field_session_date_value',
      'field_name' =&gt; 'field_session_date',
      'id' =&gt; 'mymodule_full_datetime',
      'table' =&gt; 'node__field_session_date',
    ),
    'group' =&gt; $this-&gt;t('Content'),
    'help' =&gt; $this-&gt;t('Date in the form of %format.', array('%format' =&gt; 'YYYYMMDD-HHMM')),
    'title' =&gt; $this-&gt;t('@field', array('@field' =&gt; 'Session Date (Full Datetime)')),
    'title short' =&gt; $this-&gt;t('@field (@format)', array('@field' =&gt; 'Session Date', '@format' =&gt; 'YYYYMMDD-HHMM')),
  );
}


Now you just need to add the Session Date (Full Datetime) argument to your view in place of the argument you were trying to override.