Time conversion using Bash

Time conversion using Bash

 

This article show how you can obtain the UNIX epoch time (number of seconds since 1970-01-01 00:00:00 UTC) using the Linux bash "date" command. It also shows how you can convert a UNIX epoch time to a human readable time.

Obtain UNIX epoch time using bash
Obtaining the UNIX epoch time using bash is easy. Use the build-in date command and instruct it to output the number of seconds since 1970-01-01 00:00:00 UTC. You can do this by passing a format string as parameter to the date command. The format string for UNIX epoch time is '%s'.

lode@srv-debian6:~$ date "+%s"
1234567890

To convert a specific date and time into UNIX epoch time, use the -d parameter. The next example shows how to convert the timestamp "February 20th, 2013 at 08:41:15" into UNIX epoch time.

lode@srv-debian6:~$ date "+%s" -d "02/20/2013 08:41:15"
1361346075

Converting UNIX epoch time to human readable time
Even though I didn't find it in the date manual, it is possible to use the date command to reformat a UNIX epoch time into a human readable time. The syntax is the following:

lode@srv-debian6:~$ date -d @1234567890
Sat Feb 14 00:31:30 CET 2009

The same thing can also be achieved using a bit of perl programming:

lode@srv-debian6:~$ perl -e 'print scalar(localtime(1234567890)), "\n"'
Sat Feb 14 00:31:30 2009

Please note that the printed time is formatted in the timezone in which your Linux system is configured. My system is configured in UTC+2, you can get another output for the same command.

 

date -d @1234567890

echo 1234567890 | awk '{print strftime("%c",$1)}'

0 (0)
Article Rating (No Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments
There are no comments for this article. Be the first to post a comment.
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
How to sort IP addresses in Linux
Viewed 4777 times since Thu, May 24, 2018
30 Handy Bash Shell Aliases For Linux / Unix / MacOS
Viewed 6471 times since Thu, Feb 11, 2021
Display basic information about Physical Volumes
Viewed 4530 times since Sun, Jun 3, 2018
Linux and Unix xargs command tutorial with examples
Viewed 4653 times since Fri, Jun 1, 2018
Utilities to Tidy Up Your Reports
Viewed 17193 times since Wed, May 30, 2018
10 Awk Tips, Tricks and Pitfalls
Viewed 6918 times since Wed, Aug 19, 2020
8 Practical Examples of Linux Xargs Command for Beginners
Viewed 6825 times since Fri, Jun 1, 2018
awk printf
Viewed 17454 times since Wed, Aug 19, 2020
30 Examples for Awk Command in Text Processing
Viewed 16918 times since Sat, Nov 24, 2018
Bash: String Length – How To Find Out
Viewed 3148 times since Mon, Feb 18, 2019