Linux convert timestamp to datetime

How to convert timestamps to dates in Bash?

I need a shell command or script that converts a Unix timestamp to a date. The input can come either from the first parameter or from stdin, allowing for the following usage patterns:

18 Answers 18

On systems with GNU Coreutils >= 5.3.0, e.g. Linux you can use:

@mehaase — the man page notes that the date string is too complex to be documented in the manpage, so it is described in info: info ‘(coreutils) date invocation’

info ‘Date input formats’ gets you straight to date ‘s formatting info node, with the pertinent Robert Grudin quote, and then a menu of format specifiers.

And it’s confusing because it’s not working in that way on most linux systems, because: freddy@hades ~ % date —help | grep — -r -r, —reference=FILE display the last modification time of FILE

while the comments on this answer are true, these are not rafa’s fault, and they don’t diminish his answer.

This version is similar to chiborg’s answer, but it eliminates the need for the external tty and cat . It uses date , but could just as easily use gawk . You can change the shebang and replace the double square brackets with single ones and this will also run in sh .

#!/bin/bash LANG=C if [[ -z "$1" ]] then if [[ -p /dev/stdin ]] # input from a pipe then read -r p else echo "No timestamp given." >&2 exit fi else p=$1 fi date -d "@$p" +%c 

@Bruno, @ghostdog74: On my system, gawk is (very roughly) 15% faster than date in a timed for loop consisting only of gawk ‘BEGIN < print strftime("%c", 1256571985); >‘ or date -d ‘@1256571985’ +%c with output redirected to /dev/null .

date is marginally (5%) faster than gawk for me (mac osx 10.9.2, date 8.23, gawk 4.1.1), but the real advantage of (g)awk is to accept a pipe of a column of many timestamps (see my answer below), which makes the script e.g. 250x as fast for 1000 timestamps.

Note that my answer meets the OP’s requirements as stated in the question, but the now accepted answer doesn’t.

You can use GNU date, for example,

$ sec=1267619929 $ date -d "UTC 1970-01-01 $sec secs" 

On macOS, you can run brew install coreutils and then use the gdate command, e.g. gdate —date @1660859222 which yields Thu Aug 18 14:47:02 PDT 2022 .

You can get formatted date from timestamp like this

I use this cross-platform one-liner:

date -d @1267619929 2>/dev/null || date -r 1267619929 

It should work both in macOS and modern versions of popular Linux distributions.

Since Bash 4.2 you can use printf ‘s %(datefmt)T format:

$ printf '%(%c)T\n' 1267619929 Wed 03 Mar 2010 01:38:49 PM CET 

That’s nice, because it’s a shell builtin. The format for datefmt is a string accepted by strftime(3) (see man 3 strftime ). Here %c is:

%c The preferred date and time representation for the current locale.

Now if you want a script that accepts an argument and, if none is provided, reads stdin, you can proceed as:

#!/bin/bash if (($#)); then printf '%(%c)T\n' "$@" else while read -r line; do printf '%(%c)T\n' "$line" done fi 

You can use this simple awk script:

$ echo '1098181096' | ./a.awk Tue 19 Oct 2004 03:18:16 AM PDT $ 

This doesn’t fit the first usage — sometimes I don’t want to echo the TS and use a parameter instead.

Читайте также:  Альт линукс лицензионное соглашение

On some old busybox version, date -s @ doesn’t work, and awk still does! An example without a stdin would be helpful too.

I use this when converting log files or monitoring them:

In OSX, or BSD, there’s an equivalent -r flag which apparently takes a unix timestamp. Here’s an example that runs date four times: once for the first date, to show what it is; one for the conversion to unix timestamp with %s , and finally, one which, with -r , converts what %s provides back to a string.

$ date; date +%s; date -r `date +%s` Tue Oct 24 16:27:42 CDT 2017 1508880462 Tue Oct 24 16:27:42 CDT 2017 

At least, seems to work on my machine.

$ uname -a Darwin XXX-XXXXXXXX 16.7.0 Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64 x86_64 

Источник

Convert Unix timestamp to a date string

Is there a quick, one-liner way to convert a Unix timestamp to a date from the Unix command line? date might work, except it’s rather awkward to specify each element (month, day, year, hour, etc.), and I can’t figure out how to get it to work properly. It seems like there might be an easier way — am I missing something?

12 Answers 12

With date from GNU coreutils you can do:

# date -d @0 Wed Dec 31 19:00:00 EST 1969 

Alternatively, use strftime() . It’s not available directly from the shell, but you can access it via gawk. The %c specifier displays the timestamp in a locale-dependent manner.

# echo 0 | gawk '' Wed 31 Dec 1969 07:00:00 PM EST 

Make sure to eliminate the milliseconds from the timestamp (that is only 10 digits instead of 13), otherwise you’ll get invalid results (this is true for macOS’ date).

I thought this was not working, until I realised I had a timestamp in millis. Chop off the last 3 digits, and you get the accurate time

The «Convert Unix Timestamp» link is broken. Archived version: web.archive.org/web/20200930143943/https://www.antonolsen.com/… . I would edit the post with the new URL, but the edit queue is full right now.

date -d @1278999698 +’%Y-%m-%d %H:%M:%S’ Where the number behind @ is the number in seconds

This solution works with versions of date which do not support date -d @ . It does not require AWK or other commands. A Unix timestamp is the number of seconds since Jan 1, 1970, UTC so it is important to specify UTC in the input.

date -d '1970-01-01 1357004952 sec UTC' Mon Dec 31 17:49:12 PST 2012 

If you are on a Mac, then use:

Command for getting epoch:

Specifying UTC flag is a lot simpler than that . gnu-date -u -d’@1357004952′ ; bsd-date -u -r 1357004952 :: Tue Jan 1 01:49:12 UTC 2013 Tue Jan 1 01:49:12 UTC 2013

Читайте также:  Zip сжать файл linux

You may have misread the answer. My answer is for cases when you do not have support for date -d @ and when you want to display the output in your local time zone.

As @TomMcKenzie says in a comment to another answer, date -r 123456789 is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there’s no universal guaranteed portable solution.

The -d option on many types of systems means something entirely different than GNU Date’s —date extension. Sadly GNU Date doesn’t interpret -r the same as these other implementations. So unfortunately you have to know which version of date you’re using, and many older Unix date commands don’t support either option.

Even worse, POSIX date recognizes neither -d nor -r and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime() ). (You can’t use touch -t and ls because the former does not accept a time given as seconds since the Unix Epoch.)

Note though The One True Awk available direct from Brian Kernighan does now have the strftime() function built-in as well as a systime() function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.

Источник

How to convert timestamps to dates in bash?

Bash shell scripts often require the conversion of timestamps to human-readable dates for formatting and display purposes. The conversion of timestamps to dates can be achieved using various methods, including built-in Bash commands and external tools. In this tutorial, we will explore several methods for converting timestamps to dates in Bash shell scripts.

Method 1: Using date command

To convert timestamps to dates in Bash, you can use the date command. Here are some examples:

Example 1: Convert current timestamp to date

This command will output the current timestamp in date format.

Example 2: Convert a specific timestamp to date

This command will convert the timestamp 1616157905 to date format.

Example 3: Convert multiple timestamps to dates

timestamps=(1616157905 1616157915 1616157925) for timestamp in "$[@]>"; do date -d "@$timestamp" done

This command will convert multiple timestamps to date format using a loop.

Example 4: Convert timestamps in a file to dates

while read -r timestamp; do date -d "@$timestamp" done  timestamps.txt

This command will read timestamps from a file called timestamps.txt and convert them to date format.

Example 5: Convert timestamps with a specific format to dates

date -d "2021-03-19T15:45:05Z" +"%Y-%m-%d %H:%M:%S"

This command will convert the timestamp 2021-03-19T15:45:05Z to date format with the format YYYY-MM-DD HH:MM:SS .

These are just a few examples of how to convert timestamps to dates using the date command in Bash. By using the date command, you can easily convert timestamps to dates and customize the output format according to your needs.

Method 2: Using awk command

Here is an example of how to convert timestamps to dates in Bash using the awk command:

Step 1: Create a file named «timestamps.txt» with the following content:

1613353200 1613353260 1613353320

Step 2: Run the following command in your terminal:

Step 3: You should see the following output:

2021-02-15 08:20:00 2021-02-15 08:21:00 2021-02-15 08:22:00
  • The awk command reads the contents of the «timestamps.txt» file and applies the specified action to each line.
  • The strftime function formats the timestamp into a human-readable date format. The %Y-%m-%d %H:%M:%S format string specifies the date format as «YYYY-MM-DD HH:MM:SS».
  • $1 refers to the first column of each line, which contains the timestamp value.
  • The print function outputs the formatted date to the console.

This is just one example of how to convert timestamps to dates in Bash using the awk command. There are many other ways to accomplish this task, depending on your specific needs and preferences.

Method 3: Using Perl

To convert timestamps to dates in Bash using Perl, you can use the localtime function to convert the timestamp to an array of time values, and then use the sprintf function to format the date string.

#!/usr/bin/perl $timestamp = 1619642940; @time = localtime($timestamp); $date = sprintf("%04d-%02d-%02d %02d:%02d:%02d", $time[5]+1900, $time[4]+1, $time[3], $time[2], $time[1], $time[0]); print "$date\n";

This code will output the date in the format YYYY-MM-DD HH:MM:SS .

  • The localtime function takes a Unix timestamp as an argument and returns an array of time values representing the corresponding date and time in the local timezone.
  • The array returned by localtime contains the following values: seconds, minutes, hours, day of the month, month (0-11), year (since 1900), weekday (0-6, Sunday is 0), day of the year, and whether daylight saving time is in effect.
  • The sprintf function is used to format the date string. The format string «%04d-%02d-%02d %02d:%02d:%02d» specifies the desired format: YYYY-MM-DD HH:MM:SS.
  • The values from the localtime array are passed as arguments to sprintf , with some adjustments: the year value is incremented by 1900, and the month value is incremented by 1 (since January is represented by 0).
  • The resulting formatted string is stored in the $date variable and printed to the console.

This code can be easily modified to use a variable timestamp value or to output the date in a different format.

Method 4: Using Python

To convert timestamps to dates in Bash using Python, you can use the datetime module. Here are the steps to do it:

def timestamp_to_date(timestamp): date = datetime.datetime.fromtimestamp(timestamp) return date.strftime('%Y-%m-%d %H:%M:%S')
  1. In the timestamp_to_date function, we use the fromtimestamp method of the datetime module to convert the timestamp to a datetime object. We then use the strftime method to format the date as a string.
  2. Here’s an example of how to use the timestamp_to_date function:
timestamp = 1627909265 date_string = timestamp_to_date(timestamp) print(date_string)

This will output the date string 2021-08-02 14:34:25 .

  1. If you have a list of timestamps, you can use a list comprehension to convert them all to date strings:
timestamps = [1627909265, 1627909275, 1627909285] date_strings = [timestamp_to_date(timestamp) for timestamp in timestamps] print(date_strings)

This will output the list of date strings [‘2021-08-02 14:34:25’, ‘2021-08-02 14:34:35’, ‘2021-08-02 14:34:45’] .

That’s it! With these steps, you can easily convert timestamps to dates in Bash using Python.

Источник

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