- How to get date and time using command line interface?
- 9 Answers 9
- Get current time in seconds since the Epoch on Linux, Bash
- 7 Answers 7
- Pure bash solution
- How to Get Current Date and Time in Bash Script
- Getting the Current Date and Time
- Custom Format Output
- Use Date in Shell Script:
- Available Options with date Command:
- Conclusion
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 .
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:
(The screenshot is on a virtual terminal, but it’s the same on a virtual console).
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
How to Get Current Date and Time in Bash Script
As a scripting language, Bash is widely used for system administration tasks and automation. One common task in Bash scripting is to get the current date and time. The `date` command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format
In this article, we will explore how to get the current date and time in a Bash script.
Getting the Current Date and Time
In Bash, you can use the date command to get the current date and time. By default, the date command will return the current date and time in the format of “Day_of_week Month Day Hour:Minute:Second Timezone Year”
date
Sun Feb 28 23:26:13 UTC 2023
You can also store the output of command in a variable for further use.
Custom Format Output
There are several switches, you can use to format the output of date command.
- Get date time in “MM/DD/YY HH:MM:SS” format:
date +"%Y-%m-%d %T"
2019-03-25 14:40:32
Use Date in Shell Script:
You can simply use date command inside shell script similar to use on the command prompt. Create a bash script getDateTime.sh with the following content.
Now execute the script from command line and watch output.
./getDateTime.sh
Current Date is: Mar 25, 2019 Current Date and Time is: 2019-03-25 17:18:19 Current Date and Time is: 2019-03-05 17:18:19 Current Unix epoch time is: 1488541699
Available Options with date Command:
You can find all available options of date command using –help parameter
You will find the output like below with some more options.
- %% : a literal %
- %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., 21)
- %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 ( 0..23)
- %l : hour ( 1..12)
- %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 timezone (e.g., -0400)
- %:z : +hh:mm numeric timezone (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)
Conclusion
Getting the current date and time in a Bash script is a common task that can be accomplished using the date command. By default, the date command returns the current date and time in a specific format, but you can also use a custom format string to get the date and time in any format you like. By understanding how to use the date command in a Bash script, you can build powerful automation scripts that make use of the current date and time.