Home > Net >  Python time.time() in PHP
Python time.time() in PHP

Time:09-28

Python time.time() returns timestamp with 6 decimals and PHP microtime(true) returns with 4 decimals. Is there any way in php I can get the time with 6 decimals? Thanks.

Python: 1632816181.314063

PHP: 1632816181.3140

CodePudding user response:

Can you try it this one I think working perfect according your required.

<?php 
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $timestamp = $now->getTimestamp();
    echo $data = $timestamp.".".$now->format("u");
    
    // Result :- 1632823152.201900
    
    ?>

CodePudding user response:

I've got the impression that a floating number in PHP is displayed by default with the echo or print command without all the decimals you would like.

Use printf() or sprintf() with the %f specifier and add the number of digits you would like to have. In your case 6 digits would be %.6f:

<?php

// Save the floating-point Unix timestamp just for comparing below.
$microtime = microtime(true);

echo 'echo $microtime            : ' . $microtime . "\n";
printf("printf(\"%%.6f\", \$microtime) : %.6f\n", $microtime);

// Some have proposed to create a DateTime instance.
$datetime = DateTime::createFromFormat('U.u', $microtime);
echo "DateTime::format('U.u')    : " . $datetime->format('U.u') . "\n";

This outputs the following:

echo $microtime            : 1632834055.1038
printf("%.6f", $microtime) : 1632834055.103771
DateTime::format('U.u')    : 1632834055.103800

As one can see, it seems rather weird but PHP's DateTime class is kind of dropping some precision in the process somewhere. The resulting format of u seems to be padded with zeros at the end.

Test the PHP code here

  • Related