Bash Script to Convert Unix Timestamp to Date
date -d @ to convert a Unix timestamp to a readable date, for example, date -d @1633072800 outputs the date for that timestamp.Examples
How to Think About It
date command can interpret this number and display it as a normal date by using the -d option with an @ symbol before the timestamp.Algorithm
Code
#!/bin/bash # Read timestamp from argument timestamp=$1 # Convert and print date converted_date=$(date -d @$timestamp) echo "$converted_date"
Dry Run
Let's trace the timestamp 1633072800 through the code
Get input
timestamp=1633072800
Convert timestamp to date
date -d @1633072800 returns 'Fri Oct 1 00:00:00 UTC 2021'
Print result
Output: Fri Oct 1 00:00:00 UTC 2021
| Step | Action | Value |
|---|---|---|
| 1 | Input timestamp | 1633072800 |
| 2 | date command output | Fri Oct 1 00:00:00 UTC 2021 |
| 3 | Printed output | Fri Oct 1 00:00:00 UTC 2021 |
Why This Works
Step 1: Understanding Unix timestamp
A Unix timestamp counts seconds from 1970-01-01 00:00:00 UTC, so converting it means finding the date that many seconds later.
Step 2: Using date command
The Bash date command with -d @timestamp tells the system to interpret the number as seconds since epoch and format it as a date.
Step 3: Output formatting
The output is a human-readable date string showing day, month, time, and timezone for easy understanding.
Alternative Approaches
#!/bin/bash timestamp=$1 printf '%(%Y-%m-%d %H:%M:%S)T\n' "$timestamp"
python3 -c "import datetime, sys; print(datetime.datetime.utcfromtimestamp(int(sys.argv[1])))" 1633072800
Complexity: O(1) time, O(1) space
Time Complexity
The conversion uses a direct system call without loops, so it runs in constant time.
Space Complexity
Only a few variables are used to hold input and output, so space usage is constant.
Which Approach is Fastest?
Using the Bash date command is fastest and simplest; Python adds overhead but offers flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash date -d @timestamp | O(1) | O(1) | Simple and fast conversion |
| Bash printf with format | O(1) | O(1) | Formatted output with Bash 4.2+ |
| Python one-liner | O(1) | O(1) | When date command is limited or for complex formatting |