如何将 ps -p {PID} -o etime= 中的日期格式化为 PHP 的日期时间?

How to format a date from ps -p {PID} -o etime= into PHP's datetime?

我目前 运行 在服务器上 python 脚本列出了我能找到的所有最大序列。对于演示文稿,我想指定脚本 运行.

的长度

目前,我正在使用函数 shell_exec('ps -p 1696 -o etime=') 来获取自我启动该过程以来经过的时间。 24 小时没问题,在此之后,我有一个奇怪的语法 dd-hh:mm:ss

我还没有从 php7.1 的所有日期相关函数中找到任何解决方案来解析这个值,你知道我应该怎么做才能得到时间 "readable". Regex 是这里要做的事情吗?

我的意思是我希望 php 文件回显类似 "Script Running since 2 days, 16 hours 35 minutes and 14 seconds"

的内容

这是我的 php 文件:

<?php
$time = shell_exec('ps -p 1696 -o etime='); 
// Where 1696 is the PID of the python script
echo "Collatz.py running since :" . $time; 
echo '<pre>'.file_get_contents('/var/www/html/logs.txt').'</pre>';

您可以使用正则表达式来匹配它由 ps 生成的时间字符串,将它们分组到匹配的组中,然后使用它们来构建您的字符串。

$time = shell_exec('ps -p 3646 -o etime=');

preg_match("/^(((\d*)-)?(\d*):)?(\d{2}):(\d{2})$/", $time, $matches);

$days = $matches[3];
$hours = $matches[4];
$minutes = $matches[5];
$seconds = $matches[6];

$time_string = "";
$time_string .= strlen($days) > 0 ? $days . " days, " : "";
$time_string .= strlen($hours) > 0 ? $hours . " hours " : "";
$time_string .= strlen($minutes) > 0 ? $minutes . " minutes and " : "";
$time_string .= $seconds . " seconds";

echo "Running since: " . $time_string;