Time in seconds linux

Get current time in seconds since the Epoch on Linux, Bash

I need something simple like date , but in seconds since 1970 instead of the current date, hours, minutes, and seconds. date doesn’t seem to offer that option. Is there an easy way?

Some versions of date have it and some don’t. So it’s not always present. I ran ‘type -a date’ and used a different version and that worked.

@TheBonsai that’s not part of the POSIX standard version of the ‘date’ tool. Just because your version has it (probably GNU), you shouldn’t assume everyone’s implementations do.

7 Answers 7

As recently corrected in the date manual:

%s = seconds since the Epoch (1970-01-01 00:00 UTC)

the date manpge should be changed from %s seconds since 1970-01-01 00:00:00 UTC to %s seconds since the epoch, 1970-01-01 00:00:00 UTC because I missed it in there.

Doesn’t work for me. man date does not show %s. I must have a very old version of bash (3.2.51(1) for Solaris)?

@livefree75 date is not built into bash , so your version of bash has nothing to do with which date implementation your system ships with.

Get the seconds since epoch(Jan 1 1970) for any given date(e.g Oct 21 1973).

Convert the number of seconds back to date

The command date is pretty versatile. Another cool thing you can do with date(shamelessly copied from date —help ). Show the local time for 9AM next Friday on the west coast of the US

date --date='TZ="America/Los_Angeles" 09:00 next Fri' 

Maybe it’s the version of date or because I’m using zsh (macOS Catalina) but this doesn’t work for me. Running $ date -d «Oct 21 1973» +%s outputs usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] . [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

@JoshuaPinter and others on macOS, I had the same question. man date shows that the option(s) used to parse another date string are -j and -f expectedformat on macOS. ( -d is used to set daylight savings.)

The date command above is from gnu coreutils pacakge. On mac, gnu coreutils package can be installed with brew or macports. After installing, the binary is named as gdate to distinguish it from macOS’s preinstalled /bin/date

Pure bash solution

Since bash 5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS .

$ echo $EPOCHSECONDS 1547624774 

There is also EPOCHREALTIME which includes fractions of seconds.

$ echo $EPOCHREALTIME 1547624774.371210 

EPOCHREALTIME can be converted to micro-seconds (μs) by removing the decimal point. This might be of interest when using bash ‘s built-in arithmetic (( expression )) which can only handle integers.

In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.

Читайте также:  Линукс скрипт резервного копирования

So far, all the answers use the external program date .

Since Bash 4.2, printf has a new modifier %(dateformat)T that, when used with argument -1 outputs the current date with format given by dateformat , handled by strftime(3) ( man 3 strftime for informations about the formats).

So, for a pure Bash solution:

or if you need to store the result in a variable var :

No external programs and no subshells!

Since Bash 4.3, it’s even possible to not specify the -1 :

(but it might be wiser to always give the argument -1 nonetheless).

If you use -2 as argument instead of -1 , Bash will use the time the shell was started instead of the current date. This can be used to compute elapsed times

$ printf -v beg '%(%s)T\n' -2 $ printf -v now '%(%s)T\n' -1 $ echo beg=$beg now=$now elapsed=$((now-beg)) beg=1583949610 now=1583953032 elapsed=3422 

You want to use -2 in case you have a longer running job (think of a script to control you backups) and send a mail in the end «Backup started at $somewhen completed at $now» — which can be accomplished with -2 avoiding to store a dedicated variable at the beginning.

With most Awk implementations:

Wow, had to go look this one up. This is a pragmatic solution, but not necessarily good/portable. It seems that implementations of awk srand() are typically seeded with the current date/time. The second call to srand() returns the value previously used as the seed.

POSIX compliant as well, because this is how NAWK behaves. Very nice. I was trying to remember this one and tracked down your post. Thanks.

Would it be wrong of me to suggest awk ‘BEGIN

This is an extension to what @pellucide has done, but for Macs:

To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)

$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s" 120034800 

Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the ’00:00:00′ part, it will add the time automatically. Such that «Oct 21 1973» will be parsed as «Oct 21 1973 16:19:00». That may not be what you want.

To convert your timestamp back to a date:

$ date -j -r 120034800 Sun Oct 21 00:00:00 PDT 1973 

Источник

Shell ubuntu show time with seconds code example

Solution 1: Not sure when this path changed, but as of Ubuntu 13.04 the seconds display can be set in the terminal with: To turn seconds display off: and checked with: Solution 2: GUI way: launch gnome-tweak-tool, sometimes called Advanced Settings click the Top Bar menu enable Show seconds Solution 1: In fact, the GNU command (which is the standard implementation in Ubuntu) can add date offsets directly — for example to add 3662 seconds (1hr, 1min, 2sec) to a given date However, some care is required with timezones and daylight savings — a safer option is probably to convert the original time into seconds since the start of the epoch, and add the desired offset to that before converting back to the desired format, e.g. Solution 2: You can also increment the current date easily with: says this is documented in , but I don’t feel like reading manuals now to quote it 🙂 Tested in Ubuntu 18.04, from Coreutils 8.28.

Читайте также:  Посчитать количество файлов линукс

How to show seconds on the clock in GNOME 3?

Not sure when this path changed, but as of Ubuntu 13.04 the seconds display can be set in the terminal with:

gsettings set org.gnome.desktop.interface clock-show-seconds true 

To turn seconds display off:

gsettings set org.gnome.desktop.interface clock-show-seconds false 
gsettings get org.gnome.desktop.interface clock-show-seconds 
  1. launch gnome-tweak-tool, sometimes called Advanced Settings
  2. click the Top Bar menu
  3. enable Show seconds

The most user-friendly way to do this, (on 20.04 LTS) seems to be:

sudo apt install gnome-tweak-tool 

and then launch «Tweaks» either by searching for it in Applications menu or launching gnome-tweaks from terminal.

From there you’ll see something like this:

Gnome Tweak Tool - Top Bar seconds adjustment

Shell — Timeout a command in bash without unnecessary, This answer to Command line command to auto-kill a command after a certain amount of time. proposes a 1-line method to timeout a long-running command from the bash command line: ( /path/to/slow command with options ) & sleep 5 ; kill $! But it’s possible that a given «long-running» command may finish …

How to run application for a set time in shell

You might want to use the timeout command.

timeout -k 10s 30s command 

which will run the command for 30s and kill it after 10s if still running. — Check the manpage for more options.

Here are two ways (but the timeout command suggested by mcantsin is probably better):

    Launch the command in the background, that way its PID is saved in $! and you can use that to kill it after the specified time:

firefox & sleep 30 && pkill firefox 

I have no idea what you mean by «the logs of that process» but a process’s standard error can be saved to a file with command 2> logfile.txt .

Shell Script to Demonstrate Wait Command in Linux, Approach: Creating multiple processes. Creating a text file and writing into it. Sleep 2 will pause the shell for 2 seconds. Again creating a text file and writing into it. Display that we are running multiple processes. Using wait -f to wait until all the above process has been executed successfully.

Add seconds to a given date in bash

In fact, the GNU date command (which is the standard implementation in Ubuntu) can add date offsets directly — for example to add 3662 seconds (1hr, 1min, 2sec) to a given date

$ date '+%d.%b.%Y %T' --date="2012-06-13 09:16:16 EDT + 3662 seconds" 13.Jun.2012 10:17:18 

However, some care is required with timezones and daylight savings — a safer option is probably to convert the original time into seconds since the start of the epoch, and add the desired offset to that before converting back to the desired format, e.g.

$ secs=$(date +%s --date="2012-06-13 09:16:16") $ date '+%d.%b.%Y %T' --date="@$((secs + 3662))" 13.Jun.2012 10:17:18 

You can also increment the current date easily with:

Читайте также:  Фоновый запуск команды linux

man date says this is documented in info date , but I don’t feel like reading info manuals now to quote it 🙂

Tested in Ubuntu 18.04, date from Coreutils 8.28.

$ date +%x.%H:%M:%S:%N 01/21/2014_16:02:07:422856522 

It shows a US styled data for me but see man date for more refinement. The 2 interesting options:

%N nanoseconds (000000000..999999999) %S second (00..60) 

And if you want to use the standard year, month, day format:

$ date +%Y.%m.%d_%H:%M:%S:%N 2014.07.21_16:07:52:641771706 

How to calculate time elapsed in bash script?, There are two bash internal ways to find an integer value for the number of elapsed seconds: Bash variable SECONDS (if SECONDS is unset it loses its special property). Setting the value of SECONDS to 0: SECONDS=0 sleep 1 # Process to execute elapsedseconds=$SECONDS Storing the value of the variable …

How to get system time with microsecond Resolution

will give the nano seconds since epoch To get the micro seconds just do an eval

There’s no much point asking for this kind of precision in a shell script, given that running any command (even the date command) will take at least a few hundreds of those microseconds.

In particular, you can’t really use the date command to time the execution of a command with this kind of precision.

For that, best would be to use the time command or keyword.

A few implementations allow changing the format to give you the elapsed time only with subsecond precision.

$ bash -c 'TIMEFORMAT=%3R; time date +%s' 1432210052 0.001 $ ksh -c 'TIMEFORMAT=%3R; time date +%s' 1432210094 0.001 $ zsh -c 'TIMEFMT=%*E; time date +%s' 1432210123 0.001 

Various shells have various builtin (so with minimal delay) ways to get you the time:

ksh93 and zsh have a $SECONDS variable that will give you subsecond precision if you change its type to float :

$ zsh -c 'typeset -F SECONDS=0; date; echo "$SECONDS"' Thu 21 May 13:09:37 BST 2015 0.0012110000 $ ksh -c 'typeset -F SECONDS=0; date; echo "$SECONDS"' Thu 21 May 13:09:42 BST 2015 0.0010249615 

zsh has a $EPOCHREALTIME special variable (available in the zsh/datetime module):

$ zsh -c 'zmodload zsh/datetime; echo $EPOCHREALTIME; date; echo $EPOCHREALTIME' 1432210318.7319943905 Thu 21 May 13:11:58 BST 2015 1432210318.7333047390 

ksh93 and newer versions of bash support the %(format)T format in their printf builtin, however bash doesn’t support %N (even though that’s a GNU extension), and they disagree on how to express now .

$ ksh -c 'printf "%(%s.%N)T\n" now;printf "%(%s.%N)T\n" now' 1432210726.203840000 1432210726.204068000 

(as you can see, 228 of those microseconds still elapsed between the two invocations of that builtin command).

As you said date +%s returns the number of seconds since the epoch. So,

date +%s%N returns the seconds and the current nanoseconds.

Dividing date +%s%N the value by 1000 will give in microseconds.i.e

Bash — How to get execution time of a script effectively?, My method for bash: # Reset BASH time counter SECONDS=0 # # do stuff # ELAPSED=»Elapsed: $ ( ($SECONDS / 3600))hrs $ ( ( ($SECONDS / 60) % 60))min $ ( ($SECONDS % 60))sec» Share Improve this answer edited Jan 25, 2017 at 21:34 phk 5,711 7 38 68 answered Jan 25, 2017 at 21:28 Mark 515 4 6 2

Источник

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