Skip to content
shellhacks.dev
Linux

Convert a date string to a timestamp

Convert a date string to a Unix timestamp with GNU date -d 'string' +%s. The zone is the one in TZ unless the string names one, so set it explicitly.

1 min read
Summarize in AI

A log line holds a human readable date and you need the number of seconds since 1970 to compare or subtract.

Shell
date -u -d '2026-03-05 14:00:00' +%s
TZ=UTC date -d '2026-03-05 14:00:00' +%s
TZ=Asia/Tokyo date -d '2026-03-05 14:00:00' +%s
date -d '2026-03-05 14:00:00 +0900' +%s
Text
1772719200
1772719200
1772686800
1772686800

-d parses a date string and %s prints it as epoch seconds, using the grammar in the GNU date manual. Without an explicit offset the string is read in the zone from the TZ variable or the system setting, so the Tokyo run is nine hours earlier than the UTC runs. Naming the offset in the string, as in the last line, removes the dependence on the machine.

This is GNU date. BSD and macOS date do not have -d, and date -j -f is the equivalent there. Strings such as "next friday" are accepted too, but they depend on today's date, so keep them out of scripts that must be reproducible.

Share

More snippets

Linux

Get a process's command line

Read a running process's full command line from /proc/PID/cmdline. The arguments are separated by NUL bytes, so split them with xargs -0 and not tr.

1 min read
Linux

Always use -a with -G

Add a user to a group with usermod -aG. Without -a the -G option replaces the whole supplementary group list, and the user silently loses every other group.

1 min read
Linux

Run a command with a clean environment

Run a command with an empty environment using env -i, then add back only the variables you pass. It reproduces what cron or a minimal container sees.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.