Time
1st January 1970 is special. All time used by your Pi is basically measured from then. This is defined as the start of the Unix Epoch. There is a lot of geeky detail involving leap seconds and time synchronisation over packet switching systems and such, but as far as day to day working in IOT systems is concerned, that was when time began. And it’s measured in seconds. Knowing how many seconds have elapsed since 1st January 1970 enables the time now to be calculated.
There is a protocol called N.T.P. designed to synchronise the clocks of all computers over a network to a common timebase. NTP is what ensures the time synchronisation of devices connected to the internet. Accurate timekeeping is vital to the many applications which have revolutionised and are essential to our daily lives: satellites, GPS, 5G, financial services, healthcare, and more. There is a good explanation of where your Pi gets its date and time here.
The clocks in all the computers on a network are synchronised to the master timeserver device on that network, which is itself synchronised to a remote NTP server. There is more about this at:
https://askubuntu.com/questions/14558/how-do-i-setup-a-local-ntp-server
Date and time are obtained for use in programs that use Linux by using the word date followed by various parameters that are preceded by +%
For example, open a terminal and type the following:
now=$(date +”%s”)
and the date in seconds since the start of the epoch (1st January 1970), will be loaded into the variable ‘now’
(don’t forget the space b etween date and +). To inspect the contents of ‘now’, enter:
echo $now
so that is the number of seconds from Epoch time to when you pressed <return> after entering now=$(date +”%s”) above.
Tomorrow’s date, but today’s time can be displayed by using the word tomorrow, like this:
echo $(date +”%A %d-%m-%Y” -d “tomorrow”)
yesterday also works! – or you could leave the -d “tomorrow” off and get todays date, like this:
echo $(date +”%A %d-%m-%Y”) which gives: Tuesday 20-02-2024
To display today’s date, enter:
date which gives us: Tue 20 Feb 19:10:31 GMT 2024
To store current date and time to a variable called todays, enter: todays=$(date)
To display the variable, enter: echo “$todays”
Task: Display date in mm-dd-yy format
date +”%m-%d-%y” example 02-27-07
To turn on 4 digit year display (make y upper case):
date +”%m-%d-%Y” example 02-20-2024
Just display time as hrs/mins/secs format:
date +”%T” example 15:41:58
To display the time in am/pm format, enter:
date +”%r” example 3:44:43 pm GMT
To display time in HH:MM format, type:
date +”%H-%M” example 00-50
To save time/date format to a shell variable, type the following command at the shell prompt:
NOW=$(date +”%m-%d-%Y”)
To display a variable use echo / printf command:
echo $NOW