Date linux from timestamp

How do I convert an epoch timestamp to a human readable format on the cli?

How do I convert an epoch timestamp to a human readable format on the cli? I think there’s a way to do it with date but the syntax eludes me (other ways welcome).

12 Answers 12

On Linux (specifically, with GNU coreutils ≥5.3):

With older versions of GNU date, you can calculate the relative difference to the UTC epoch:

date -d '1970-01-01 UTC + 1234567890 seconds' 

If you need portability, you’re out of luck. The only time you can format with a POSIX shell command (without doing the calculation yourself) line is the current time. In practice, Perl is often available:

perl -le 'print scalar localtime $ARGV[0]' 1234567890 

+1 for the comment about the lack of portability (why doesn’t the POSIX spec include a way to do this? grr)

@ChrisMarkle GNU man pages are often woefully incomplete. “The date string format is more complex than is easily documented here but is fully described in the info documentation.” To wit: gnu.org/software/coreutils/manual/html_node/…

The info date is quite complete. The entry at 28.9 Seconds since the Epoch explains in detail about the @timestamp.

If your epoch time is in milliseconds instead of seconds, remove the last three digits before passing it to date -d :

$ date -d @1455086371603 Tue Nov 7 02:46:43 PST 48079 #Incorrect 

This gives incorrect data. Remove the last three digits.

$ date -d @1455086371 Tue Feb 9 22:39:31 PST 2016 #Correct after removing the last three digits. You may remove and round off the last digit too. 

I have seen that WebLogic Application server mostly returns data time values with milliseconds and no dots when using scripting tool. e.g., lastSuccessfulConnectionUse=1455086371603

date -d @1190000000 Replace 1190000000 with your epoch

$ printf '%(%FT%T%z)T\n' 1234567890 2009-02-13T23:31:30+0000 

(where %FT%T%z is the strftime() -type format, here using standard unambiguous format which includes the UTC offset ( %z ))

That syntax is inspired from ksh93 .

In ksh93 however, the argument is taken as a date expression where various and hardly documented formats are supported.

For a Unix epoch time, the syntax in ksh93 is:

Читайте также:  Qt creator debugger linux

ksh93 however seems to use its own algorithm for the timezone and can get it wrong. For instance, in mainland Britain, it was summer time all year in 1970, but:

$ TZ=Europe/London bash -c 'printf "%(%c)T\n" 0' Thu 01 Jan 1970 01:00:00 BST $ TZ=Europe/London ksh93 -c 'printf "%(%c)T\n" "#0"' Thu Jan 1 00:00:00 1970 

ksh93 (and zsh’s strftime builtin) support subsecond, not bash yet:

$ ksh -c 'printf "%(%FT%T.%6N%z)T\n" 1234567890.123456789' 2009-02-13T23:31:30.123456-0000 $ zsh -c 'zmodload zsh/datetime; strftime %FT%T.%6.%z 1234567890 123456780' 2009-02-13T23:31:30.123457+0000 

Источник

Guide to Converting Timestamps in a Column to a Date

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

1. Overview

Text transformation is part and parcel of data analysis activity. One such scenario is where we’ve occurrences of epoch timestamps in the dataset and want to convert it to a human-readable date format.

In this tutorial, we’ll learn how to convert timestamps in a column to a comprehensible date format.

2. Scenario Setup

Let’s take a look at the sample data.txt file with a tabular structure:

$ cat data.txt 1681322596 a1 b1 1649786596 a2 b2 1618250596 a3 b3

We must notice that the first column contains timestamps which are convenient to use within computer programs but not so much useful for the human eye.

3. Using awk

In this section, we’ll use GNU awk to transform the timestamps to corresponding date values.

3.1. Using strfstime() Time Function

We can use the stftime() function available in GNU awk to convert a timestamp to a date string:

strftime (format, timestamp)

Let’s start by learning how we can convert a single timestamp using the stftime() function:

$ date +%s | tee >(awk '<$0=strftime("%Y-%m-%d %H:%M:%S", $0); print($0);>') 1681232216 2023-04-11 16:56:56

We must note that we used the date command to get the current timestamp, followed by the tee command to show it before sending it to the awk command.

Now, let’s use the logic for processing the data.txt file:

$ awk '<$1=strftime("%Y-%m-%d %H:%M:%S", $1); print $0>' data.txt 2023-04-12 18:03:16 a1 b1 2022-04-12 18:03:16 a2 b2 2021-04-12 18:03:16 a3 b3

Great! We’ve got this right.

3.2. Calling an External Program

We can also call an external program and capture its output within an awk script. As a result, we can leverage the date command for our use case.

First, let’s see how we can use the date command for timestamp-to-date conversion:

$ timestamp=$(date +%s); echo $timestamp; date [email protected]$timestamp +"%F %H:%M:%S" 1681325421 2023-04-12 18:50:21

Next, let’s use this within an awk command:

$ date +%s | \ tee \ >(awk '[email protected]"$0 " +\"%F %H:%M:%S\""; cmd | getline result; close(cmd); print(result)>') 1681325991 2023-04-12 18:59:51

Finally, let’s write an awk script to process the timestamps in the data.txt file:

$ awk '< cmd="date [email protected]"$1 " +\"%F %H:%M:%S\""; cmd | getline $1; close(cmd); print($0) >' data.txt 2023-04-12 18:03:16 a1 b1 2022-04-12 18:03:16 a2 b2 2021-04-12 18:03:16 a3 b3

4. Using sed

Despite being a powerful text-processing utility, sed doesn’t have built-in time functions for timestamp-to-date conversion. So, we need to call an external program within the sed script to solve our use case.

Let’s begin by learning to convert a single timestamp by calling the date command from within the sed script:

$ date +%s | tee >(sed -n -E -e "s/(.*)/date [email protected]\\1 +\"%F %H:%M:%S\"/ep") 1681233473 2023-04-11 17:17:53

We must note that we used the e function to execute the replacement string as an instruction set. Further, let’s also remember that we need to escape symbols such as \1 (first substitution group) and double quotes.

Now, we can write our sed script for converting timestamps in the data.txt file:

$ sed -n -E \ > -e "s/^(9*)(.*)/date [email protected]\\1 +\"%F %H:%M:%S\" | tr -d '\n'; echo \"\\2\";/ep" \ > data.txt 2023-04-12 18:03:16 a1 b1 2022-04-12 18:03:16 a2 b2 2021-04-12 18:03:16 a3 b3

Over here, we’ve used two substitution groups, namely \1 and \2, for the first and rest of the columns, respectively. Furthermore, we’ve used the tr command to remove the trailing newline from the output of the preceding date command.

5. Using Bash Script

We can use Bash arrays and iterations to parse the tabular contents from the data.txt file. Furthermore, we can use the date command to convert the timestamps to date strings and concatenate them with the rest of the fields.

Let’s look at the timestamp-to-date.sh script in its entirety:

$ cat timestamp-to-date.sh #!/bin/bash readarray -t rows < data.txt TIME_COL=1 for row in "$" do col_count=$(echo $row | wc -w) cur_col=1 while : do cell_val=$(echo -e $row | cut -d" " -f$cur_col) if [[ $cur_col == $TIME_COL ]] then cell_val=$(date [email protected]$ +"%F %H:%M:%S") fi printf "%s " "$cell_val" cur_col=$[$cur_col+1] [[ $cur_col > "$col_count" ]] && break done echo "" done exit 0

We must note that we’re using the cut command to extract individual column values.

Now, let’s see the script in action:

$ ./timestamp-to-date.sh 2023-04-12 18:03:16 a1 b1 2022-04-12 18:03:16 a2 b2 2021-04-12 18:03:16 a3 b3

6. Conclusion

In this article, we explored multiple utilities such as awk, sed, and Bash script to convert timestamps to date strings.

Источник

How to Convert a Linux Epoch Timestamp to Date on the Command Line

Epoch timestamp is the time passed since January 1, 1970 at 00:00:00 UTC in seconds. These timestamps are commonly used in computing and are particularly useful for dealing with dates and times in a standard and consistent manner. Reading and interpreting these timestamps can be difficult for people who are unfamiliar with epoch timestamps. Please read this guide if you also want to know how to convert a Linux epoch timestamp to date on the command line.

How to Convert a Linux Epoch Timestamp to Date on the Command Line

The date command is a standard Unix utility that displays and manipulates the dates and times. It is the pre-installed utility in most Linux distributions and can convert an epoch timestamp to a human-readable date and time. Run the following command to convert an epoch timestamp:

In the previous command, you can replace the as the number of seconds since January 1, 1970 at 00:00:00 UTC.

For example, to convert the epoch timestamp 1674000000 which corresponds to January 18, 2023 at 00:00:00 GMT, use the following command:

The -d option specifies the date and time in a format that is understood by the date command. The “@” symbol indicates that the argument is an epoch timestamp instead of a different time format.

The date command supports several different output formats which you can specify using the + option and a format string. For example, to display the date and time in the YYYY-MM-DD HH:MM:SS format, use the following command:

You can find more information on the format codes on the manual date page (man date).

Conclusion

This is all about the simple way to convert a Linux epoch timestamp to date on the command line. This can be useful for converting timestamps in log files, database entries, and other data sources into an easier-to-read and understandable format. With a simple command line argument, you can quickly and easily convert an epoch timestamp into a date and time that is usable for your purposes.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

Оцените статью
Adblock
detector