前言
timestamp 是我們在紀錄 log 時重要的依據,
通常我們會使用從「1970年1月1日」開始以秒為單位計算,
不斷1秒 +1 的這個值作為 timestamp
目前總共累積至 10位數 (精準度到秒)
- 無聊想更了解 timestamp 換算,可以玩玩這個網站
1000000000 = 2001年09月09日09點46分40秒
2000000000 = 2033年05月18日11點33分20秒
而紀錄時,通常會使用 13位 (也就是精準度到 ms),
因為程式運算很快,有時候一秒就能處理非常多的事情,
(相對來說,很多程式處理一行都是 ms 等級的時間。)
記錄到 ms,我們更能精確的抓準可能是在程式中的哪一的部分出錯。
python 取得 timestamp
import time
print(time.time()) # 10位,s
from datetime import datetime
ts = datetime.now().timestamp()
print(ts)
注意
如果使用 datetime.utcnow().timestamp() 會是「當前時區」的 timestamp,
以台灣來說就是 UTC+8 了
延伸閱讀: [Python] 你知道 datetime.utcnow().timestamp() 不是 Unix Timestamp 嗎?
延伸閱讀: Python 使用 timestamp 的注意事項
C++ 取得 timestamp
C++ 17 或以前
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr); // 10位,s
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
C++ 20
在 chrono 這個 library 提供了 time_since_epoch 這個新的函式可以使用,
不過好像大部分公司的系統都沒更到那麼新…
上面的方法應該還是比較好用的。
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
// 10位,s
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
// 13位,ms
auto millisec_since_epoch = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
cout << "milliseconds since epoch: " << millisec_since_epoch << endl;
}
C++ 其他方法 – 1
#include <sys/time.h>
struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; // 13位, ms
time_t s = tp.tv_sec * 1000; // 10位, s
C++ 其他方法 – 2
int64_t current_timestamp;
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
current_timestamp = ((int64_t)time.tv_sec)*1000 + time.tv_nsec/1000000;
cout << "current_timestamp = " << current_timestamp << endl;
變形:自製 function timeMs (呼應 time(NULL) 的實作方法 )
int64_t timeMs(int64_t *t)
{
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
return ((int64_t)time.tv_sec)*1000 + time.tv_nsec/1000000;
}
Linux/Bash 取得 timestamp
string
timestamp=$(date +%s)
取得 s 的方法 (10位)
date +"%s" # 10位, s
取得 ms 的方法 (19 digits (nanoseconds))
date +"%s.%N" # 19 digits (nanoseconds)
取整
echo '('`date +"%s.%N"` ' * 1000000)/1' | bc # 取整
function,取得現在的時間
timestamp() {
date +"%T" # current time
}
結合 watch 使用,用 terminal 來顯示 timestamp (自動更新)
10 digits
watch -n .1 date +"%s"
19 digits (nanoseconds)
watch -n .1 date +"%s.%N"