I have a Raspberry Pi 2 Model B that I use as a mini server and I'd like to get an accurate reading of the times the system is switched on. The problem is not the shutdown times, which are logged correctly, but the startup ones, since the Pi doesn't have an RTC. This means that every startup the Pi has to connect to a NTP time server, but it does that only after logging the startup time, which is the First of January, 3 AM (12 midnight UTC) before syncing. I'd like a way to log startup times after the clock has been synced, even if not the default log file.
As already stated in the question: since the Raspberry Pi does not have a real time clock RTC with a buffered power supply, its clock is reset to 0 after each reboot. Time is only an integer number with its reference being the time of 00:00:00 UTC on 1 January 1970 (Unix epoch). There is no way of knowing the accurate time without feeding that information from an external source, e.g. sync'ing with a NTP time server.
If the time of start up is of utter importance it has to be calculated from full system log, e.g.
journalctl -b for the log of the current boot.
We know that start-up took place at
Jan 01 00:00:00, now follow the log (not necessarily manually) to the point where systemd claims
Time has been changed. Parse the new time, parse the last old time to get the number of seconds it has been running (e.g. 15 seconds), substract, done.
As always there is a little pitfall. Unfortunately it is possible that network time synchronization might try to do its work before networks are up. It then notices a jump backwards and resets the clock to the last recorded timestamp - a time more or less near the last shutdown of the Pi. But the idea to solve the problem is the same, parse the full log for
Time has been changed, and calculate the desired time.
Jan 01 01:00:15 j systemd: Starting Network Time Synchronization... Jan 01 01:00:15 j systemd: Starting Update UTMP about System Boot/Shutdown... Jan 01 01:00:15 j systemd-timesyncd: System clock time unset or jumped backwards, restoring from recorded timestamp: Thu 2015-12-24 13:33:31 CET Dec 24 13:33:31 j systemd: Time has been changed .... Dec 24 13:33:48 j systemd-networkd: eth0: Configured Dec 24 13:33:48 j systemd-timesyncd: Network configuration changed, trying to establish connection. Dec 27 20:18:10 j systemd: Time has been changed Dec 27 20:18:10 j systemd-timesyncd: Synchronized to time server 188.8.131.52:123 (2.arch.pool.ntp.org).
You do not say what distribution you are running, but Raspbian has
fake-hwclock which should restore the time to what it was when shut down. This is also in the latest Ubuntu, and could be installed on other distributions.
You could always try deferring boot until after networking has started.
If time is important to you why not install a RTC. They are available for less than $2 on ebay. The
DS3231 works on 3.3V and is easy to install on the Pi.