Tag Archives: timestamp

Most common Bash date commands for timestamping

From time to time I get asked how to use the date command to generate a timestamp. Here is an idiot-friendly script you can post for reference in your team’s bin/ if you get interrupted about timestamp questions or have an aversion to typing phrases like “man date” (with or without a space).

All but the first and last two produce filename-friendly strings. (Thanks to Rich for the reminder to include UTC and timezoned stamps here):

#! /bin/bash

# An overly obvious reference for most commonly requested bash timestamps
# Now all you Mac fags can stop pestering me.

cat << EOD
        Format/result         |       Command              |          Output
------------------------------+----------------------------+------------------------------
YY-MM-DD_hh:mm:ss             | date +%F_%T                | $(date +%F_%T)
YYMMDD_hhmmss                 | date +%Y%m%d_%H%M%S        | $(date +%Y%m%d_%H%M%S)
YYMMDD_hhmmss (UTC version)   | date --utc +%Y%m%d_%H%M%SZ | $(date --utc +%Y%m%d_%H%M%SZ)
YYMMDD_hhmmss (with local TZ) | date +%Y%m%d_%H%M%S%Z      | $(date +%Y%m%d_%H%M%S%Z)
YYMMSShhmmss                  | date +%Y%m%d%H%M%S         | $(date +%Y%m%d%H%M%S)
YYMMSShhmmssnnnnnnnnn         | date +%Y%m%d%H%M%S%N       | $(date +%Y%m%d%H%M%S%N)
Seconds since UNIX epoch:     | date +%s                   | $(date +%s)
Nanoseconds only:             | date +%N                   | $(date +%N)
Nanoseconds since UNIX epoch: | date +%s%N                 | $(date +%s%N)
ISO8601 UTC timestamp         | date --utc +%FT%TZ         | $(date --utc +%FT%TZ)
ISO8601 Local TZ timestamp    | date +%FT%T%Z              | $(date +%FT%T%Z)
ISO8601 UTC timestamp + ms    | date --utc +%FT%T.%3NZ     | $(date --utc +%FT%T.%3NZ)
EOD

If executed, it will produce the (obvious) output:

        Format/result         |       Command              |          Output
------------------------------+----------------------------+------------------------------
YY-MM-DD_hh:mm:ss             | date +%F_%T                | 2016-10-14_09:19:53
YYMMDD_hhmmss                 | date +%Y%m%d_%H%M%S        | 20161014_091953
YYMMDD_hhmmss (UTC version)   | date --utc +%Y%m%d_%H%M%SZ | 20161014_001953Z
YYMMDD_hhmmss (with local TZ) | date +%Y%m%d_%H%M%S%Z      | 20161014_091953JST
YYMMSShhmmss                  | date +%Y%m%d%H%M%S         | 20161014091953
YYMMSShhmmssnnnnnnnnn         | date +%Y%m%d%H%M%S%N       | 20161014091953225313813
Seconds since UNIX epoch:     | date +%s                   | 1476404393
Nanoseconds only:             | date +%N                   | 230837143
Nanoseconds since UNIX epoch: | date +%s%N                 | 1476404393232904886
ISO8601 UTC timestamp         | date --utc +%FT%TZ         | 2016-10-14T00:19:53Z
ISO8601 Local TZ timestamp    | date +%FT%T%Z              | 2016-10-14T09:19:53JST
ISO8601 UTC timestamp + ms    | date --utc +%FT%T.%3NZ     | 2016-10-14T00:19:53.237Z