How to get time on 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).

Читайте также:  Сделать контроллер домена linux

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 

Источник

Get current time in hours and minutes

I’m trying to collect information from a system and I need to get the current time in hours and minutes. Currently I have:

why use awk? date supports a wide variety of formatting characters and would be happy to generate the EXACT output you want, without extra tools. date +%H:%M

6 Answers 6

Running man date will give all the format options

%a locale's abbreviated weekday name (e.g., Sun) %A locale's full weekday name (e.g., Sunday) %b locale's abbreviated month name (e.g., Jan) %B locale's full month name (e.g., January) %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g., 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour, space padded ( 0..23); same as %_H %l hour, space padded ( 1..12); same as %_I %m month (01..12) %M minute (00..59) %n a newline %N nanoseconds (000000000..999999999) %p locale's equivalent of either AM or PM; blank if not known %P like %p, but lower case %r locale's 12-hour clock time (e.g., 11:11:04 PM) %R 24-hour hour and minute; same as %H:%M %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %t a tab %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale's date representation (e.g., 12/31/99) %X locale's time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric time zone (e.g., -0400) %:z +hh:mm numeric time zone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %. z numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z alphabetic time zone abbreviation (e.g., EDT) 

Источник

Читайте также:  Umount linux device is busy

How to get date and time using command line interface?

How can I get current date/time in terminal. I mostly start up my system in text(console) mode and need the command to know the current date/time.

9 Answers 9

The date command will show you the date and time.

man date will show you how to control the output to whatever format you need, if you want something other than the standard output. For example:

will output the date and time in the format 14:09:22 09/06/2015

An easier to read version of the man page can be found on Ubuntu Man Pages

Time as the command line prompt:

A little fancier, enclosed in brackets:

Add the user and localhost with the time, all within brackets:

Looks like: [ DrPete on LittleSorrel 10:34 AM ~ ]

Reset prompt to default #: PS1=»# «

To make the prompt permanently available, add the prompt line of your choice, i.e.,

Can’t help it, we are rolling now. add colors, define them in .profile to make them easier to set up:

 # Install GNU coreutils bk="\[\033[0;38m\]" #means no background and white lines txtBlue="\[\033[0;34m\]" #letter color blue txtRed="\[\033[0;31m\]" #letter color red txtCyan="\[\033[1;36m\]" #letter color cyan txtWhite="\[\033[1;37m\]" #letter color white txtYellow="\[\033[1;33m\]" #letter color yellow 

Then a superfancy colored prompt would be:

PS1="[ $txtYellow\u on $txtCyan\h $txtRed\@ $txtWhite\w$bk ]" 

My first answer — so now that I am no longer a virgin — expand in what way, narrative or link to CLI prompt info?

There are a list of command used for time and date:

$ date Tue Jun 9 18:04:30 EEST 2015 
$ zdump EEST EEST Tue Jun 9 15:05:17 2015 EEST 
$ sudo hwclock Tue 09 Jun 2015 06:05:55 PM EEST -0.656710 seconds 
sudo apt-get install xview-clients 
$ ntpdate 26 Jun 10:48:34 ntpdate[4748]: no servers can be used, exiting 

With Ubuntu 15.04 (systemd) there is also timedatectl which shows you the time and allows you to change it and more in man timedatectl .

Читайте также:  Linux which files in directory

Without arguments it gives

% timedatectl Warning: Ignoring the TZ variable. Reading the system's time zone setting only. Local time: ke 2015-06-10 10:31:59 EEST Universal time: ke 2015-06-10 07:31:59 UTC RTC time: ke 2015-06-10 07:31:59 Time zone: Europe/Helsinki (EEST, +0300) NTP enabled: yes NTP synchronized: yes RTC in local TZ: no DST active: yes Last DST change: DST began at su 2015-03-29 02:59:59 EET su 2015-03-29 04:00:00 EEST Next DST change: DST ends (the clock jumps one hour backwards) at su 2015-10-25 03:59:59 EEST su 2015-10-25 03:00:00 EET

And another nice feature that I have used is timedatectl set-ntp true which activates systemd-timesyncd which is inbuild SNTP (Simple Network Time Protocol) client which syncs your clock with remote server.

Although all the answers here are correct, you need to use the date command manually to see the time whenever you want, and the output will mix with normal output of your command. This is mostly ok, but sometime is not practical.

You can add the date command to your prompt which will show a (fixed) clock every time the shell is ready for the command, or you can use one of the terminal multiplexer that have a status line. My preferred one (although I admit the oldest one) is GNU screen.

In console or in a terminal, say via ssh , if you use screen, among zillions of different things you can do (I used to think about screen as unavoidable for working when I had just a text terminal) you have the option — which is normally in the default configuration — of having a clock in the status line:

Screen on a terminal

(The screenshot is on a virtual terminal, but it’s the same on a virtual console).

Источник

How can I display the current time & date setting?

I don’t know of a single file, but this may give you the info needed:

cat /etc/timezone grep UTC /etc/default/rcS date # hardware clock sudo hwclock --show 

Best example (IMHO) using timedatectl (in command-line/terminal):

$ timedatectl Local time: Thu 2014-07-24 19:51:23 IST Universal time: Thu 2014-07-24 14:21:23 UTC Timezone: Asia/Kolkata (IST, +0530) NTP enabled: no NTP synchronized: no RTC in local TZ: no DST active: n/a 

Visit the manpage for more settings and further information.

Additional info that may also be useful: to change time zone do «sudo timedatectl set-timezone America/Los_Angeles» (use your own time zone instead of America/Los_Angeles. Timezones can be found with timedatectl list-timezones)

Fri 22 Nov 2019 04:31:50 PM UTC

Check out info date , and for example date +’%z’

For the time zone, you can use geolocation:

$ curl https://ipapi.co/timezone America/Chicago 
$ curl http://ip-api.com/line?fields=timezone America/Chicago 

If you need a formatted area and time zone, you can use:

$ grep `date +%Z` /etc/timezone Etc/UTC 
PS> Get-TimeZone Id : Europe/Vilnius DisplayName : (UTC+02:00) Eastern European Standard Time StandardName : Eastern European Standard Time DaylightName : Eastern European Summer Time BaseUtcOffset : 02:00:00 SupportsDaylightSavingTime : True 

I suspect this won’t be popular answer in a Linux community, but I really like the verb-noun convention. It makes it easier for me to remember commands, and it will also work on all distributions with PowerShell installed 🙂

Источник

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