Datetime processing#

Anyone who has worked for a while with computers will tell you that dealing with time is hard. A gigantic amount of effort has gone into trying to map the human understanding of time, combining a messy universe with thousands of years of human culture and innovation, to something computers can actually deal with.

We’ll look at how to deal with some common and fairly simple cases using the date command. date by default prints a human–readable datetime with second resolution and the current time zone:

Input formatting#

We can also give date a specific input datetime with --date=DATETIME. It has complex rules for parsing all manner of human–readable input, but the safest is to specify a machine–readable RFC 3339 string:

Output formatting#

For RFC 3339 output use --rfc-3339=PRECISION:

You may have heard of ISO 8601 as the machine–readable datetime format, but RFC 3339 has some advantages: it allows a space separator between the date and time for readability, and it only allows a full stop between the integer and fractional seconds. date --iso-8601=ns on the other hand uses a comma separator, which is not appropriate in an English–speaking locale.

In addition to making the datetime easy to parse, RFC 3339 datetimes (in the same time zone) can be trivially sorted. So if you ever want to parse your datetimes or sort your lines simply use RFC 3339.

 

This page is a preview of The newline Guide to Bash Scripting

No discussions yet