Obtaining sub-second precision in Linux environments requires leveraging either shell built-ins or external libraries. The GNU date command supports nanosecond resolution via the %N directive, while Python’s standard library offers flexible multipliers for milliseconds or microseconds.
# Capture current timestamp with nanosecond precision
NANO_TS=$(date '+%s%N')
echo "Nanoseconds: $NANO_TS"
When working within Python, adjusting the multiplication factor on time.time() determines the output unit:
import time
millisecond_ts = int(round(time.time() * 1000))
microsecond_ts = int(round(time.time() * 1_000_000))
nanosecond_ts = int(round(time.time() * 1_000_000_000))
print(millisecond_ts, microsecond_ts, nanosecond_ts)
Standardized date formatting is essential for logging and database storage. The - delimiter produces ISO-compliant strings, whereas stripping delimiters yields compact identifiers:
ISO_FORMAT=$(date '+%Y-%m-%d %H:%M:%S')
COMPACT_ID=$(date '+%Y%m%d%H%M%S')
echo "$ISO_FORMAT $COMPACT_ID"
Extracting raw epoch seconds provides a reliable baseline for mathematical operations. This approach eliminates timezone parsing overhead during interval calculations:
EPOCH_SEC=$(date '+%s')
echo "Unix Epoch: $EPOCH_SEC"
Measuring execution duration can be achieved by capturing start and end epochs, then aplying arithmetic expansion for better performance than legacy expr:
START_EPOCH=$(date '+%s')
sleep 5
END_EPOCH=$(date '+%s')
DURATION=$((END_EPOCH - START_EPOCH))
echo "Elapsed: ${DURATION}s"
Relative date arithmetic allows shifting timelines forward or backward without manual calendar calculations:
YESTERDAY_ISO=$(date -d '-1 day' '+%Y-%m-%d %H:%M:%S')
WEEK_AGO_EPOCH=$(date -d '-7 days' '+%s')
MONTH_BACK=$(date -d '-30 days' '+%Y-%m-%d %H:%M:%S')
QUARTER_AGO=$(date -d '-90 days' '+%Y-%m-%d %H:%M:%S')
echo "$YESTERDAY_ISO | $WEEK_AGO_EPOCH | $MONTH_BACK | $QUARTER_AGO"
Adjusting specific timestamps by minutes or hours utilizes inline offset syntax:
BASE_DT="2024-07-13 12:00:00"
OFFSET_1M=$(date -d "$BASE_DT + 1 minute" '+%Y%m%d%H%M%S')
OFFSET_30M=$(date -d "$BASE_DT + 30 minutes" '+%Y%m%d%H%M%S')
OFFSET_60M=$(date -d "$BASE_DT + 60 minutes" '+%Y%m%d%H%M%S')
echo "$OFFSET_1M | $OFFSET_30M | $OFFSET_60M"
Converting continuous numeric strings into structured datetime formats relies on substring extraction:
RAW_TS="20240715123045"
FORMATTED_DT="${RAW_TS:0:4}-${RAW_TS:4:2}-${RAW_TS:6:2} ${RAW_TS:8:2}:${RAW_TS:10:2}:${RAW_TS:12:2}"
echo "Parsed: $FORMATTED_DT"
System clock synchronization and timezone configuration are managed through standard utilities:
sudo timedatectl set-timezone Asia/Shanghai
sudo date -s '2024-07-15 08:45:00'
Processing session logs often involves calculating active versus completed durations. Given a dataset containing creation and closure times, dynamic epoch conversion ensures accurate uptime tracking:
# For active sessions
TODAY=$(date '+%Y-%m-%d')
CREATE_EPOCH=$(date -d "$TODAY $SESSION_START" '+%s')
CURRENT_EPOCH=$(date '+%s')
ACTIVE_DUR=$((CURRENT_EPOCH - CREATE_EPOCH))
# For completed sessions
CLOSE_EPOCH=$(date -d "$TODAY $SESSION_END" '+%s')
COMPLETED_DUR=$((CLOSE_EPOCH - CREATE_EPOCH))
Retrieving runtime thresholds from embedded databases prevents hardcoded values in scripts. A temporary SQL script isolates configuration queries and cleans CSV artifacts:
QUERY_TS=$(date '+%s%N')
SQL_FILE="query_${QUERY_TS}.sql"
OUTPUT_FILE="result_${QUERY_TS}.txt"
{
echo ".mode csv"
echo ".output $OUTPUT_FILE"
echo "SELECT FirstValue FROM data_dictionary WHERE MasterKey='TIMEOUT' AND SlaveKey='T1';"
echo ".output stdout"
} > "$SQL_FILE"
sqlite3 "$DB_PATH" < "$SQL_FILE" >/dev/null 2>&1
TIMEOUT_VAL=$(cat "$OUTPUT_FILE" | tr -d '"' | tr -d '\r' | xargs)
rm -f "$SQL_FILE" "$OUTPUT_FILE"
Automating daily log archival at midnight requires checking hour boundaries. Both pre-midnight and post-midnight detection methods trigger file rotation:
# Pre-midnight boundary check
PREV_DAY=$(date -d '-1 day' '+%m%d')
NOW_HH=$(date '+%H')
[[ "$NOW_HH" == "00" ]] && mv nohup.out "nohup.out.${PREV_DAY}" && : > nohup.out
# Post-midnight boundary check
NEXT_DAY=$(date -d '+1 day' '+%m%d')
[[ "$NOW_HH" == "23" ]] && mv nohup.out "nohup.out.$(date '+%m%d')" && : > nohup.out
Bidirectional conversion between human-readable dates and Unix epochs streamlines timestamp auditing:
TEXT_DT="2024-09-06 17:17:41"
TO_EPOCH=$(date -d "$TEXT_DT" '+%s')
FROM_EPOCH=$(date -d "@$TO_EPOCH" '+%Y-%m-%d %H:%M:%S')
echo "Original: $TEXT_DT | Epoch: $TO_EPOCH | Reconverted: $FROM_EPOCH"
Final interval verification combines epoch subtraction with explicit output formatting:
DT_A="2024-09-06 17:17:41"
DT_B="2024-09-06 18:17:41"
EP_A=$(date -d "$DT_A" '+%s')
EP_B=$(date -d "$DT_B" '+%s')
DELTA_SECS=$((EP_B - EP_A))
echo "Duration: $DELTA_SECS seconds"