Tuesday, February 11, 2020

Converting Between Human Time and Absolute Time in the Shell

This is really more of a note-to-self but it may also be useful for other readers.

Converting between various time zones, including UTC time, is both a pain and error-prone. A better solution is to use absolute time. Thankfully, Unix provides such a time: the so-called Epoch time, which is the integer count of the number of seconds since January 1, 1970.

Timestamps are both very important and often overlooked: the moreso in the context of performance analysis, where time is the zeroth metric. In fact, my preferred title would have been, Death to Time Zones but that choice would probably have made it harder to find the main point here, later on, viz., how to use the Unix epoch time.

Although there are web pages that facilitate such time conversions, there are also shell commands that are often more convenient to use, but not so well known. With that in mind, here are some examples (for future reference) of how to convert between human-time and Unix time.

Examples

The following are the bash shell commands for both MacOS and Linux.

MacOS and BSD

Optionally see the human-readable date-time:

[njg]~% date
Tue Feb 11 10:04:32 PST 2020
Get the Unix integer time for the current date:

[njg]~% date +%s
1581444272
Resolve a Unix epoch integer to date-time:

[njg]~% date -r 1581444272
Tue Feb 11 10:04:32 PST 2020

Linux

Optionally see the human-readable date-time:

[njg]~% date
Tue Feb 11 10:04:32 PST 2020
Get the Unix integer time for the current date:

[njg]~% date +%s
1581444272
Resolve a Unix epoch integer to date-time:

[njg]~% date -d @1581444272
Tue Feb 11 18:04:32 UTC 2020

No comments: