Bash Epoch Timestamp
The date command is the standard tool for Unix timestamps in Bash. Note: Linux (GNU date) and macOS (BSD date) have different syntax for some operations.
Get the current Unix timestamp
Bash
date +%s # seconds (works on Linux + macOS)
date +%s%3N # milliseconds (GNU/Linux only)
date +%s%N # nanoseconds (GNU/Linux only)
# Store in a variable
NOW=$(date +%s)
echo $NOWConvert epoch to human-readable date
Bash — Linux (GNU date)
date -d @1700000000
date -d @1700000000 '+%Y-%m-%d %H:%M:%S' # 2023-11-14 22:13:20
date -d @1700000000 --utc # force UTC output
date -d @1700000000 '+%Y-%m-%dT%H:%M:%SZ' --utc # ISO 8601Bash — macOS (BSD date)
date -r 1700000000
date -r 1700000000 '+%Y-%m-%d %H:%M:%S'
date -r 1700000000 -u '+%Y-%m-%dT%H:%M:%SZ' # ISO 8601 UTCConvert date string to epoch
Bash — Linux (GNU date)
date -d "2023-11-14 22:13:20" +%s
date -d "2023-11-14T22:13:20Z" +%s # ISO 8601 UTC
date -d "yesterday" +%s
date -d "next monday" +%s
date -d "2 hours ago" +%sBash — macOS (BSD date)
date -j -f "%Y-%m-%d %H:%M:%S" "2023-11-14 22:13:20" +%s
date -j -f "%Y-%m-%dT%H:%M:%S" "2023-11-14T22:13:20" +%sDate arithmetic in scripts
Bash
NOW=$(date +%s)
ONE_HOUR_AGO=$((NOW - 3600))
ONE_DAY_LATER=$((NOW + 86400))
THIRTY_DAYS_AGO=$((NOW - 30 * 86400))
# Check if a file was modified in the last hour
FILE_MOD=$(date -r myfile.log +%s 2>/dev/null || stat -c %Y myfile.log)
if (( NOW - FILE_MOD < 3600 )); then
echo "File modified within the last hour"
fiMeasure script execution time
Bash
START=$(date +%s)
# ... your script here ...
sleep 2
END=$(date +%s)
ELAPSED=$((END - START))
echo "Elapsed: ${ELAPSED}s"Cross-platform solution (Python fallback)
Bash
# Works on both Linux and macOS
python3 -c "import time; print(int(time.time()))"
# Convert epoch to date cross-platform
python3 -c "from datetime import datetime,timezone; print(datetime.fromtimestamp(1700000000,tz=timezone.utc))"→ Use the live epoch converter to convert any shell timestamp instantly.