DateTime with microseconds
/!\ EDIT /!\
I now use https://github.com/briannesbitt/Carbon, the rest of this answer is just here for historical reasons.
END EDIT
I decided to extend the class DateTime
using the tips you all gave me.
The constructor takes a float (from microtime
) or nothing (in this case it will be initialized with the current "micro-timestamp").
I also overrided 2 functions that were important : setTimestamp
and getTimestamp
.
Unfortunately, I couldn't solve the performances issue, although it's not as slow as I thought.
Here's the whole class :
<?php
class MicroDateTime extends DateTime
{
public $microseconds = 0;
public function __construct($time = 'now')
{
if ($time == 'now')
$time = microtime(true);
if (is_float($time + 0)) // "+ 0" implicitly converts $time to a numeric value
{
list($ts, $ms) = explode('.', $time);
parent::__construct(date('Y-m-d H:i:s.', $ts).$ms);
$this->microseconds = $time - (int)$time;
}
else
throw new Exception('Incorrect value for time "'.print_r($time, true).'"');
}
public function setTimestamp($timestamp)
{
parent::setTimestamp($timestamp);
$this->microseconds = $timestamp - (int)$timestamp;
}
public function getTimestamp()
{
return parent::getTimestamp() + $this->microseconds;
}
}
c# datetime with microseconds propper format
Simplest custom implementation I could think of..
ulong ExtendedTimestamp = 99;
ulong timeStampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = DateTime.Now;
string dateWithMicroseconds = startDate.AddTicks((long)timeStampInTicks).ToString("HH:mm:ss.ffffff");
string dateHHmmss = dateWithMicroseconds.Split('.')[0];
string timeffffff = dateWithMicroseconds.Split('.')[1];
int precision = 3;
string milliSecs = timeffffff.Substring(0, precision);
string microSecs = timeffffff.Substring(precision, timeffffff.Length - precision);
string customFormat = string.Format("{0}:{1}:{2}", dateHHmmss, milliSecs, microSecs);
How can I change microseconds in a datetime?
The simplest way to do that is by slicing
it
Example:
x = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
print(x)
Getting date format m-d-Y H:i:s.u from milliseconds
php.net says:
So use as simple:Microseconds (added in PHP 5.2.2). Note that
date()
will always generate000000
since it takes an integer parameter, whereasDateTime::format()
does support microseconds ifDateTime
was created with microseconds.
$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0]."<br>";
Recommended and use dateTime()
class from referenced: $t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro, $t) );
print $d->format("Y-m-d H:i:s.u"); // note at point on "u"
Note u
is microseconds (1 seconds = 1000000 µs).Another example from php.net:
$d2=new DateTime("2012-07-08 11:14:15.889342");
Reference of dateTime()
on php.netI've answered on question as short and simplify to author. Please see for more information to author: getting date format m-d-Y H:i:s.u from milliseconds
Convert 16-digit datetime string to datetime with microseconds
You can use the handy DATETIMEFROMPARTS
:
DECLARE @s nvarchar(16) = '2022020804180454';
SELECT DATETIMEFROMPARTS(LEFT(@s,4), --year
SUBSTRING(@s,5,2), --month
SUBSTRING(@s,7,2), --day
SUBSTRING(@s,9,2), --hour
SUBSTRING(@s,11,2), --minute
SUBSTRING(@s,13,2), --second
SUBSTRING(@s,15,2)*10 --millisecond
)
Python: Parse timestamp string with 7 digits for microseconds to datetime
Using dparser
:
import dateutil.parser as dparser
dt_1 = '2019-02-16T10:41:20.6080000+01:00'
print("Datetime: {}".format(dparser.parse(dt_1,fuzzy=True)))
OUTPUT:Datetime: 2019-02-16 10:41:20.608000+01:00
If you want the date component:print("Date: {}".format(dparser.parse(dt_1,fuzzy=True).date()))
OUTPUT:Date: 2019-02-16
Concatenate 'date' and 'time in microseconds' in Dataframe to datetime format
Solution if ms
are miliseconds:
You can split Time
column by whitespace to df1
, then first column 0
convert to timedeltas, and for second remove ms
, casting to intgers and also convert to timedeltas with unit='ms' by to_timedelta
, date convert to datetimes by to_datetime
and sum all together:
df1 = df['Time'].str.split(expand=True)
df['datetime'] = (pd.to_datetime(df['Date']) +
pd.to_timedelta(df1[0]) +
pd.to_timedelta(df1[1].str.replace('ms','').astype(int), unit='ms'))
print (df)
Date Time MP ElapsedTime \
0 2020/08/02 21:21:46 0ms 230400 0.040
1 2020/08/02 21:21:46 82191ms 97 0.049
2 2020/08/02 21:21:46 164383ms 21 0.058
3 2020/08/02 21:21:46 246575ms 0 0.068
4 2020/08/02 21:21:46 328767ms 0 0.078
330404 2020/08/03 03:00:33 0ms 2037 4323.555
330405 2020/08/03 03:00:33 40513ms 1964 4323.564
330406 2020/08/03 03:00:33 81026ms 1975 4323.574
330407 2020/08/03 03:00:33 121539ms 1949 4323.586
330408 2020/08/03 03:00:33 162052ms 1877 4323.597
datetime
0 2020-08-02 21:21:46.000
1 2020-08-02 21:23:08.191
2 2020-08-02 21:24:30.383
3 2020-08-02 21:25:52.575
4 2020-08-02 21:27:14.767
330404 2020-08-03 03:00:33.000
330405 2020-08-03 03:01:13.513
330406 2020-08-03 03:01:54.026
330407 2020-08-03 03:02:34.539
330408 2020-08-03 03:03:15.052
Related Topics
Symfony 3.1.5 Warning: Sessionhandler::Read(): Session Data File Is Not Created by Your Uid
How to Select Year and Month from the Created_At Attributes of Database Table in Laravel 5.1
Calculate the Difference Between 2 Timestamps in PHP
PHP Warning: Unknown: Input Variables Exceeded 1000
How to Convert Ldap Timestamp to Unix Timestamp
Zend Framework - Multiplate Navigation Blocks
How Does This Pcre Pattern Detect Palindromes
How to Resize and Convert an Uploaded Image to a Png Using Gd
How to Change the Default Netbeans 7 Project Directory
PHP Upload File Enhance Security
Upgrading Laravel 5.5 to 5.6 Error
Codeigniter $This->Input->Post() Empty While $_Post Is Working Correctly
Use PHP to Check If Page Was Accessed with Ssl
Determine If User Is Using Proxy
Create a Zip File Using PHP Class Ziparchive Without Writing the File to Disk
How to Disable the Back Browser Button After User Press Logout and Destroy Session