How to Get Timestamp in Bash
Quick Answer: Get a Timestamp in Bash
Use date +%s to get the current Unix timestamp (seconds since January 1, 1970). For milliseconds, use date +%s%3N. Timestamps are universal, timezone-independent ways to represent time, perfect for logging, comparisons, and calculations.
Quick Comparison: Timestamp Formats
| Format | Output | Best For | Precision |
|---|---|---|---|
| %s | Seconds | File ages, comparisons | 1 second |
| %s%3N | Milliseconds | Performance timing | 1 millisecond |
| %s%6N | Microseconds | High-precision timing | 1 microsecond |
| Human-readable | YYYY-MM-DD HH:MM:SS | Logs, display | 1 second |
Bottom line: Use date +%s for standard timestamping, date +%s%3N for higher precision, and convert with date -d @timestamp when you need to display a timestamp as human-readable.
What is a Timestamp?
A timestamp is a way to represent a specific moment in time as a single number. The most common format is Unix time (or Epoch time): the number of seconds since January 1, 1970, 00:00:00 UTC. Timestamps are incredibly useful for logging, measuring elapsed time, or comparing when events occurred.
Method 1: Getting the Current Timestamp
The simplest way to get a timestamp:
#!/bin/bash
# Get current Unix timestamp
timestamp=$(date +%s)
echo "Current timestamp: $timestamp"
# Output: 1740148245
# Get timestamp with milliseconds
timestamp_ms=$(date +%s%3N)
echo "With milliseconds: $timestamp_ms"
# Output: 1740148245123
When to Use Current Timestamp
- You need the time for logging events
- You’re measuring how long something takes
- You want a unique identifier for files/records
- You need timezone-independent time representation
Method 2: Converting Timestamps to Human-Readable Format
Timestamps are useful for machines, but humans need readable dates:
#!/bin/bash
# Get a timestamp
timestamp=1740148245
# Convert to readable format
echo "Date: $(date -d @$timestamp '+%Y-%m-%d %H:%M:%S')"
# Output: 2026-02-21 14:30:45
echo "Full format: $(date -d @$timestamp '+%A, %B %d, %Y at %I:%M %p')"
# Output: Saturday, February 21, 2026 at 02:30 PM
When to Use Timestamp Conversion
- You’re displaying timestamp data to users
- You need to debug timestamp-related issues
- You’re converting database timestamps to readable form
- You want to understand what a timestamp means
Method 3: Measuring Elapsed Time
Calculate how long something takes:
#!/bin/bash
# Get start time
start_time=$(date +%s)
# Simulate work
echo "Processing..."
sleep 2
# Get end time
end_time=$(date +%s)
# Calculate elapsed time
elapsed=$((end_time - start_time))
echo "Elapsed time: $elapsed seconds"
# Output: Elapsed time: 2 seconds
When to Use Elapsed Time Measurement
- You’re monitoring script performance
- You need to know how long a process takes
- You’re benchmarking different approaches
- You want to add timing to logs
Practical Examples
Script Performance Monitor
#!/bin/bash
# Track script execution time
script_start=$(date +%s)
echo "Starting backup process..."
# Simulate backup work
for i in {1..5}; do
echo "Backing up file $i..."
sleep 1
done
echo "Backup complete"
# Calculate and display execution time
script_end=$(date +%s)
total_time=$((script_end - script_start))
echo ""
echo "Execution Summary:"
echo "=================="
echo "Start: $(date -d @$script_start '+%H:%M:%S')"
echo "End: $(date -d @$script_end '+%H:%M:%S')"
echo "Duration: $total_time seconds"
Logging with Timestamps
Add timestamps to log entries:
#!/bin/bash
logfile="/var/log/myapp.log"
log_message() {
local message="$1"
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[$timestamp] $message" >> "$logfile"
}
log_message "Application started"
log_message "Processing user request"
log_message "Application stopped"
Log file output:
[2026-02-21 14:30:45] Application started
[2026-02-21 14:30:47] Processing user request
[2026-02-21 14:30:52] Application stopped
Converting Between Timestamp Formats
Different timestamps for different needs:
#!/bin/bash
now_seconds=$(date +%s)
now_milliseconds=$(date +%s%3N)
now_microseconds=$(date +%s%6N)
echo "Seconds: $now_seconds"
echo "Milliseconds: $now_milliseconds"
echo "Microseconds: $now_microseconds"
# Output:
# Seconds: 1740148245
# Milliseconds: 1740148245123
# Microseconds: 1740148245123456
Comparing Timestamps
Check which event happened first:
#!/bin/bash
# Two events with timestamps
file1_mtime=$(stat -c %Y /var/log/file1.log)
file2_mtime=$(stat -c %Y /var/log/file2.log)
if (( file1_mtime > file2_mtime )); then
echo "file1.log was modified more recently"
else
echo "file2.log was modified more recently"
fi
Scheduling Based on Timestamps
Run tasks at specific times:
#!/bin/bash
# Run a task only once per day
TASKFILE="/tmp/daily_task"
today=$(date +%Y-%m-%d)
last_run=""
if [ -f "$TASKFILE" ]; then
last_run=$(cat "$TASKFILE")
fi
if [ "$last_run" != "$today" ]; then
echo "Running daily task..."
# Do daily work here
echo "$today" > "$TASKFILE"
else
echo "Daily task already run today"
fi
Backup Rotation
Delete old backups based on timestamps:
#!/bin/bash
BACKUP_DIR="/backups"
RETENTION_SECONDS=$((30 * 24 * 60 * 60)) # 30 days in seconds
NOW=$(date +%s)
for backup in "$BACKUP_DIR"/backup_*.tar.gz; do
if [ -f "$backup" ]; then
file_mtime=$(stat -c %Y "$backup")
age=$((NOW - file_mtime))
if (( age > RETENTION_SECONDS )); then
echo "Deleting old backup: $(basename "$backup")"
rm "$backup"
fi
fi
done
Handling Timestamp Calculations
#!/bin/bash
# Current timestamp
now=$(date +%s)
# Calculate various time offsets
one_hour_ago=$((now - 3600))
one_day_ago=$((now - 86400))
one_week_ago=$((now - 604800))
echo "Now: $(date -d @$now '+%Y-%m-%d')"
echo "1 hour ago: $(date -d @$one_hour_ago '+%Y-%m-%d %H:%M:%S')"
echo "1 day ago: $(date -d @$one_day_ago '+%Y-%m-%d')"
echo "1 week ago: $(date -d @$one_week_ago '+%Y-%m-%d')"
Important Notes
- Use
date +%sfor portability across different systems - Millisecond precision requires
date +%s%3N(check yourdateversion) - For calculations, convert to/from timestamps for accuracy
- Timestamps are always in UTC when using the
@prefix withdate -d - Remember that timestamps are seconds since epoch - divide by 86400 to get days
- The
statcommand shows file modification time with-c %Y
Quick Reference
# Get current timestamp
date +%s
# Get with milliseconds
date +%s%3N
# Convert timestamp to date
date -d @1740148245 '+%Y-%m-%d %H:%M:%S'
# Calculate seconds between two times
start=$(date +%s)
# ... do something ...
end=$(date +%s)
elapsed=$((end - start))
# Compare timestamps
[ $time1 -gt $time2 ] && echo "time1 is later"
Summary
Timestamps are essential for any script that needs to track time - from logging to performance measurement to scheduling tasks. Master the Unix timestamp format and you’ll be able to implement time-based logic reliably and portably across different systems.