Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8425823
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T04:22:47+00:00 2026-06-10T04:22:47+00:00

I’m trying to query mysql for an average of SUM time (taken from datetime

  • 0

I’m trying to query mysql for an average of SUM time (taken from datetime fields) for multiple records in order to get an output like: 22:38

My datetime field checkin_time contains data like:

2012-03-16 22:48:00 // the time here: 22:48 is what's interesting to me
2012-03-16 02:28:32
2012-03-16 00:28:47
0000-00-00 00:00:00

My plan was to extract and select the sum time from all datetime fields, then converting the sum to unix timestamp, divide the sum by total number of records and finally convert it back to time his format. This (see code below) however gives me nothing, no error no nothing. I also realized empty fields like: 0000-00-00 00:00:00 were not to be taken into account to produced relevant data.

Can anyone please help me pointing out the mistakes or perhaps explain the theory behind how you would do it? This is what i got so far:

Edit: Thanks to Damiqib for suggesting a working SQL query, still not entirely correct though. The code below outputs 01:00 when it should be 23:15 something.

 $getCheckinTime = mysql_query("SELECT COUNT(id), SEC_TO_TIME( AVG( TIME_TO_SEC(  `checkin_time` ) ) ) AS averageTime FROM guests WHERE checkin_time != '0000-00-00 00:00:00'") or die(mysql_error());
while($checkIn = mysql_fetch_array($getCheckinTime)) { 

    $timestamp = strtotime($checkIn['averageTime']);
    $UnixTimeStamp = date("Y-m-d H:i:s", $timestamp); //converting to unix
    $avgUnix = $UnixTimeStamp / $checkIn['COUNT(id)']; // calculating average
    $avgTime = date('H:i', $avgUnix); // convert back to time his format
    echo $avgTime; //outputs 01:00, got to be incorrect should be 23:15 something

}

Thanks in advance

Edit: Solution (thanks to Damiqib):

$avgCheckinTime = array();
$getCheckinTime = mysql_query("SELECT TIME(`checkin_time`) AS averageTime    FROM guests    WHERE checkin_time !=  '0000-00-00 00:00:00'") or die(mysql_error());
while($checkIn = mysql_fetch_array($getCheckinTime)) { 

    array_push($avgCheckinTime, $checkIn['averageTime']);
}

// = array('22:00:00', '22:30:00'...)
    $times = $avgCheckinTime;

    $fromReplace = array('22' => '00',
                   '23' => '01',
                   '00' => '02',
                   '01' => '03',
                   '02' => '04',
                   '03' => '05',
                   '04' => '06',
                   '05' => '07');

  $timeSum = 0;

  //Iterate through all given times and convert them to seconds
  foreach ($times as $time) {
   if (preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$time, $parse)) {
  $timeSum += (int) $fromReplace[$parse['hours']] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'] . '<br />';

  //echo $time . ' ' . ($fromReplace[$parse['hours']] *3600) .  '<br />'; 
  }
}

   $toReplace = array('00' => '22',
                 '01' => '23',
                 '02' => '00',
                 '03' => '01',
                 '04' => '02',
                 '05' => '03',
                 '06' => '04',
                 '07' => '05');

 $time = explode(':', gmdate("H:i:s", $timeSum / count($times)));

 $averageCheckinTime = $toReplace[$time[0]] . ':' . $time[1] . ':' . $time[2];

 //This is the final average time biased between 22-05
 echo $averageCheckinTime;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T04:22:48+00:00Added an answer on June 10, 2026 at 4:22 am

    This seemed to work with my test data:

    SELECT SEC_TO_TIME(AVG(TIME_TO_SEC(`time`))) AS averageTime
    FROM guests 
    WHERE checkin_time != '0000-00-00 00:00:00'
    

    UPDATE:

    -- Table structure for table `guests`
    CREATE TABLE `guests` (
      `checkin_time` datetime NOT NULL,
      KEY `checkin_time` (`checkin_time`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    -- Dumping data for table `guests`
    INSERT INTO `guests` VALUES('2012-08-17 17:30:00');
    INSERT INTO `guests` VALUES('2012-08-17 18:30:00');
    INSERT INTO `guests` VALUES('2012-08-17 19:30:00');
    INSERT INTO `guests` VALUES('2012-08-17 20:30:00');
    INSERT INTO `guests` VALUES('2012-08-17 21:30:00');
    
    
    Showing rows 0 - 0 (1 total, Query took 0.0003 sec)
    SELECT SEC_TO_TIME( AVG( TIME_TO_SEC(  `checkin_time` ) ) ) AS averageTime
    FROM guests
    WHERE checkin_time !=  '0000-00-00 00:00:00'
    LIMIT 0 , 30
    

    Result

    averageTime
    19:30:00
    

    At least with my test data this seems to be working?

    ANOTHER UPDATE

    <?php
    
      /*
        SELECT TIME(`checkin_time`) AS averageTime
        FROM guests
        WHERE checkin_time !=  '0000-00-00 00:00:00'
      */
    
      // = array('22:00:00', '22:30:00'...)
      $times = RESULT_FROM_QUERY_AS_AN_ARRAY_OF_TIMES;
    
      $fromReplace = array('22' => '00',
                           '23' => '01',
                           '00' => '02',
                           '01' => '03',
                           '02' => '04',
                           '03' => '05',
                           '04' => '06',
                           '05' => '07');
    
      $timeSum = 0;
    
      //Iterate through all given times and convert them to seconds
      foreach ($times as $time) {
        if (preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$time, $parse)) {
          $timeSum += (int) $fromReplace[$parse['hours']] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'] . '<br />';
    
          echo $time . ' ' . ($fromReplace[$parse['hours']] *3600) .  '<br />'; 
        }
      }
    
      $toReplace = array('00' => '22',
                         '01' => '23',
                         '02' => '00',
                         '03' => '01',
                         '04' => '02',
                         '05' => '03',
                         '06' => '04',
                         '07' => '05');
    
      $time = explode(':', gmdate("H:i:s", $timeSum / count($times)));
    
      $averageCheckinTime = $toReplace[$time[0]] . ':' . $time[1] . ':' . $time[2];
    
      //This is the final average time biased between 22-05
      echo $averageCheckinTime;   
    
    ?>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to select an H1 element which is the second-child in its group
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.