Date format suitable for file names

It is rare that you want to write something without later wanting to be able to read it back. One common way of organizing files that are generated regularly is by time stamp. If you want to add a timestamp to a file name, you can do so using the date command.

In order for the filenames to sort in the right order, you want the name to go from largest unit to smallest.

Here is an example that creates a filename-suitable string formed Year->second. I remove all unnecessary formatting characters.

date --rfc-3339=seconds | sed -E -e 's! |-|:!!g'

The date command reads the current date/time on the local system. –rfc-3339=seconds produces output that looks like this:

$ date --rfc-3339=seconds 
2021-11-03 10:57:14-04:00

In order to keep the regular expression concise inside the sed command, the -E switch tells it to use extended regular expressions, including the alternation character ‘|’ . Thus, the regex ‘ |-|:’ matches a space, a dash, and a colon.

2 thoughts on “Date format suitable for file names

  1. I use:
    date +%Y%m%d%H%M%S
    No sed necessary.
    If you want the time zone, append %z.

  2. I defer to the convention used by Google Drive. Many users will be familiar with this convention set by the internet giant. When I download multiple files, Google Drive zips them into a .zip file named like drive-download-20210903T001625Z-001.zip I therefore use

    prefix=whatever
    ext=.zip
    filename=”$prefix-$(date –utc +’%Y%m%dT%H%M%SZ’)$ext”

    If I know for sure that all parties will be in the local time zone, I drop the –utc and Z parts:

    filename=”$prefix-$(date +’%Y%m%dT%H%M%S’)$ext”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.