How to Get Unix Timestamp in Milliseconds Using Bash Shell


4 views

When working with timestamps in Bash, we often need different levels of precision. While the standard Unix timestamp counts seconds since January 1, 1970 (UTC), many modern applications require millisecond precision for accurate timing measurements, logging, or synchronization.

The most straightforward method uses the date command with %s format specifier and arithmetic operations:

# Get timestamp in milliseconds
timestamp=$(( $(date '+%s') * 1000 ))
echo $timestamp

For systems with GNU date (common on Linux), we can get even more precise results by combining nanoseconds and milliseconds:

# Full precision millisecond timestamp
timestamp=$(( $(date '+%s%N') / 1000000 ))
echo $timestamp

For systems without GNU date (like macOS/BSD), we can use this portable approach:

# Works on both Linux and macOS
timestamp=$(perl -MTime::HiRes -e 'print int(1000 * Time::HiRes::time)')
echo $timestamp

When calling these commands frequently in scripts, consider these optimized approaches:

# Using bash built-ins where possible
now=${EPOCHREALTIME}  # Bash 5.0+
millis=${now%*.*}${now#*.}
millis=${millis:0:13}
echo $millis

Here's how you might use millisecond timestamps in real scripts:

#!/bin/bash

start_time=$(( $(date '+%s%N') / 1000000 ))

# Your script operations here
sleep 1

end_time=$(( $(date '+%s%N') / 1000000 ))
elapsed=$(( end_time - start_time ))

echo "Operation took ${elapsed} milliseconds"

Unix timestamps represent the number of seconds that have elapsed since January 1, 1970 (UTC). For more precise timing requirements, we often need milliseconds precision.

The simplest way to get milliseconds in Bash is using the date command with some arithmetic:

timestamp=$(($(date +%s) * 1000))
echo $timestamp

For even more precise measurements, we can use nanoseconds and convert to milliseconds:

timestamp=$(($(date +%s%N)/1000000))
echo $timestamp

Here are some other approaches you might find useful:

Using Python

python -c 'import time; print(int(time.time() * 1000))'

Using Perl

perl -e 'print time * 1000, "\n"'

Remember that Unix timestamps are always in UTC. If you need to work with local time zones, you'll need additional conversion:

timestamp=$(TZ=UTC date +%s%N | cut -b1-13)
echo $timestamp

For scripts that need to get timestamps frequently, the date command can be relatively slow. In such cases, consider:

# Cache the command if possible
get_timestamp() {
  echo $(($(date +%s%N)/1000000))
}
  • Logging with precise timestamps
  • Performance measurement
  • Unique ID generation
  • Synchronization between systems

If you encounter issues:

  • Verify your Bash version (bash --version)
  • Check if date supports nanoseconds (date +%N)
  • Consider using alternative methods if precision is critical