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
Dealing with Funny Files
Viewed 3251 times since Wed, May 30, 2018
Linux: Repeat Command N Times – Bash FOR Loop
Viewed 3611 times since Mon, Feb 18, 2019
O’Reilly’s CD bookshelf
Viewed 14396 times since Wed, Jun 27, 2018
HowTo: Clear BASH History
Viewed 2670 times since Mon, Feb 18, 2019
View Config Files Without Comments
Viewed 2766 times since Mon, May 21, 2018
Transform XML to CSV Format | Unix String Pattern Manipulation The Ugly Way
Viewed 7392 times since Sun, Jan 9, 2022
8 Practical Examples of Linux Xargs Command for Beginners
Viewed 6133 times since Fri, Jun 1, 2018
awk printf
Viewed 16376 times since Wed, Aug 19, 2020
Bash: String Length – How To Find Out
Viewed 2700 times since Mon, Feb 18, 2019
30 Examples for Awk Command in Text Processing
Viewed 16105 times since Sat, Nov 24, 2018