I'm converting a std::chrono::time_point<std::chrono::high_resolution_clock> timestamp using
std::chrono::duration_cast<std::chrono::milliseconds>(
getTimestamp().time_since_epoch()
).count()
to a 64 bit timestamp with millisecond precision. This is needed for some serialization in between of data. Later on I need to convert those timestamps back to a std::chrono::time_point<std::chrono::high_resolution_clock> for further processing. What is the proper way to do this in C++11?
Convert the number of milliseconds to a duration and add it to an epoch time_point:
auto epoch = std::chrono::time_point<std::chrono::high_resolution_clock>();
auto since_epoch = std::chrono::milliseconds(deserialised);
auto timestamp = epoch + since_epoch;
Related
Can anyone explain how to convert a Hex TimeDateStamp DWORD value into human readable format?
I'm just curious as to how a value such as 0x62444DB4 is converted into
"Wednesday, 30 March 2022 10:31:48 PM"
I tried googling of course and could not find any explanation. But there are online converters available.
But I'm just interested in converting these values for myself.
Your value is a 32-bit Timestamp.
Your datetime value is a 32-bit Unix Timestamp: The number of seconds since 1/1/1970.
See https://unixtime.org/
In most programming languages you can work with the hexadecimal notation directly.
Implementation should not be done by one person alone, since a lot of engineering goes into it. Leap years, even leap seconds, timezones, daylight savings time, UTC... all these things need to be addressed when working with a timestamp.
I have added my rough calculation below as a demonstration. Definitely use an existing package or library to work with timestamps.
See the JavaScript code below for demonstration.
There I multiply your value by 1000 because JavaScript works in Milliseconds. But otherwise this applies the same to other systems.
let timestamp = 0x62444DB4;
let dateTime = new Date(timestamp * 1000);
console.log('Timestamp in seconds:', timestamp);
console.log('Human-Readable:', dateTime.toDateString() + ' ' + dateTime.toTimeString());
// Rough output, just for the time.
// Year month and day get really messy with timezones, leap years, etc.
let hours = Math.floor(timestamp/3600) % 24;
let minutes = Math.floor(timestamp/60) % 60;
let seconds = Math.floor(timestamp) % 60;
console.log('Using our own time calculation:', hours + ':' + minutes + ':' + seconds);
I have a dataset with three columns : Start, Stop and Date
Observations in my Start and Stop are time type.
I have the following two values in my Start and Stop columns:
24:49:00 and 25:16:00
As there are both over 24 hours format.
I would like to convert those two values to the following:
24:49:00 to 00:49:00
and
25:16:00 to 01:16:00
How to do this in both SAS and proc sql ?
Thank you !
Do you need to convert them? Use the TIMEPART() function.
start_day=datepart(start);
start_time=timepart(start);
format start_time tod8.;
Or do you just want to display them that way?
format start stop tod8.;
Start/Stop time-24:00:00 like this:
data _null_;
start='25:16:14't;
point='24:00:00't;
_start=start-point;
put _start;
format _start time8.;
run;
SAS Time and DateTime values use seconds as their fundamental unit.
Thus you can use either modulus arithmetic or TIMEPART function to extract the less than 24 hour part of a > 24 hour time value.
data have;
start = '24:49:00't;
stop = '25:16:00't;
start_remainder = mod(start, '24:00't); * modulus arithmetic;
stop_remainder = mod(stop, '24:00't);
start_timepart = timepart(start); * TIMEPART function;
stop_timepart = timepart(stop);
format start: stop: time10.;
run;
After the computation do not expect start_remainder is less than stop_remainder to be always true.
Working on a c++ 11 function that returns a string from an epoch timestamp with millisecond resolution. Doing this with the current date seems straight forward:
auto currentTime = std::chrono::system_clock::now( );
const time_t time = std::chrono::system_clock::to_time_t( currentTime );
However, I'm having a hard time finding out to initialize without now() and instead using a timestamp from the past. Trying to do this using std library, but can't quite see how to initialize the time_point using a past timestamp.
How about using the std::chrono::duration class. Below is an example.
unsigned long noOfClockTicks = 10111111111; // Mar 16 10:31:59 2018
std::chrono::duration<unsigned long> duration(noOfClockTicks);
system_clock::time_point pastTime(duration);
Adjust noOfClockTicks to get the correct value you want or you can even calculate it from std::chrono::system_clock::now().
In libc there are two functions to convert from system time to calendar time - gmtime and localtime, but only localtime has inverse function - mktime. Why there is no inverse function for gmtime, and if there shouldn't be any, why gmtime exists?
I've found this piece of code work satisfactorily:
namespace std {
time_t timegm(tm* _Tm)
{
auto t = mktime(_Tm);
return t + (mktime(localtime(&t)) - mktime(gmtime(&t)));
}
}
which satifies the test:
auto t1 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto t2 = std::timegm(std::gmtime(&t1));
EXPECT_EQ(t1, t2);
To explain the existence of gmtime(), some context is required:
gmtime() will convert a timestamp representation (number of seconds since 1970-01-01 00:00:00) to broken-down time representation (aka, struct tm), assuming that the timestamp timezone is UTC:
The gmtime() function converts the calendar time timep to
broken-down time representation, expressed in Coordinated Universal
Time (UTC). It may return NULL when the year does not fit into an
integer. The return value points to a statically allocated struct
which might be overwritten by subsequent calls to any of the date
and time functions.
In the other hand, localtime() takes in consideration the [local] system timezone (including daylight saving):
The localtime() function converts the calendar time timep to
broken- down time representation, expressed relative to the user's
specified timezone. The function acts as if it called tzset(3) and
sets the external variables tzname with information about the
current timezone, timezone with the difference between Coordinated
Universal Time (UTC) and local standard time in seconds, and
daylight to a nonzero value if daylight savings time rules apply
during some part of the year.
Note that the number of seconds since 1970-01-01 00:00:00 differ from timezone to timezone (when it was 1970-01-01 00:00:00 in New York, it clearly wasn't in, for instance, Tokyo).
The mktime() converts a struct tm to a time_t value (number of seconds since 1970-01-01 00:00:00) based on the [local] system timezone, and should not be interpreted as the inverse of any particular function (such as localtime() or gmtime()), as the inverse term may be [wrongly] interpreted as a safe cross-system conversion:
The mktime() function converts a broken-down time structure,
expressed as local time, to calendar time representation. The
function ignores the values supplied by the caller in the tm_wday
and tm_yday fields. The value specified in the tm_isdst field informs
mktime() whether or not daylight saving time (DST) is in effect
for the time supplied in the tm structure: a positive value means DST
is in effect;
There is also a non-portable function (for GNU and BSD systems) called timegm(), which assumes a UTC timezone, such as gmtime() does.
References
Blockquoted text is retrieved from parts of release 3.74 of the Linux man-pages project.
I'm considering to use Protocol Buffers for data exchange between a Linux and a Windows based system.
Whats the recommended format for sending date/time (timestamp) values? The field should be small when serialized.
There is Timestamp message type since protobuf 3.0, that's how to create it in model:
syntax = "proto3";
import "google/protobuf/timestamp.proto";
message MyMessage {
google.protobuf.Timestamp my_field = 1;
}
timestamp.proto file contains examples of Timestamp using, including related to Linux and Windows programs.
Example 1: Compute Timestamp from POSIX time().
Timestamp timestamp;
timestamp.set_seconds(time(NULL));
timestamp.set_nanos(0);
Example 2: Compute Timestamp from POSIX gettimeofday().
struct timeval tv;
gettimeofday(&tv, NULL);
Timestamp timestamp;
timestamp.set_seconds(tv.tv_sec);
timestamp.set_nanos(tv.tv_usec * 1000);
Example 3: Compute Timestamp from Win32 GetSystemTimeAsFileTime().
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
// A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
// is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
Timestamp timestamp;
timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
Although you aren't saying which languages you are using or what kind of precision you need, I would suggest using Unix time encoded into a int64. It is fairly easy to handle in most languages and platforms (see here for a Windows example), and Protobufs will use a varint-encoding keeping the size small without limiting the representable range too much.
In the latest protobuf version (3.0) - For C#, Timestamp a WellKnownType is available. Check this