Python - set current time ?

Hello all,
Just today I connected a DS3231 Real Time Clock module to my Pi - to use
when it cannot connect to the internet to get its current time from an NTP
server..
I'm using python to retrieve the date and time from the RTC module and
display it. But now I'm stuck at the point where I need to set Raspberry
Pi's clock with it. I've been googeling for at least half an hour, but
can't seem to find how to *set* the current time.
De closest I have been is to execute
"datetime.datetime(2019,11,02,16,06,0) - which gets ignored without any kind
of error or warning message ...
Added problem: The Pi might (ofcourse) have problems with "a mere user"
trying to change the system clock, and might need some kind of "sudo". How
do I do that from within "Thonny" (in the "shell" window) ?
Regards,
Rudy Wieser
Reply to
R.Wieser
Loading thread data ...
formatting link

--
Luuk
Reply to
Luuk
You don't. Yes you need sudo. I'd use the command line: "sudo hwclock -s" (see: man hwclock). Only works if your rtc is recognised. Check with "timedatectl status".
Not sure how automatic the sync from rtc to system clock is. I mean, if an rtc is present, does the system time updater automatically use it after every reboot? Or does it just keep pinging ntp servers, even if they can't be reached? So, look into that. Alternatively, remove all ntp/fakehwclock services then add to /etc/rc.local: "hwclock -s". When the rtc has lost its time, first set the system clock, then: "hwclock -w" to copy to the rtc.
Reply to
A. Dumas
Alexandre,
Really ? No straightforward way to set the system clock from within a python script (ran with sudo privileges) ? Thats ... odd.
I know that I can do that, but thats not my intention.
For all intents-and-purposes you can forget all about the RTC, leaving just the "using python, how do I set the time?" part.
Regards, Rudy Wieser
Reply to
R.Wieser
On Sat, 2 Nov 2019 16:14:54 +0100, "R.Wieser" declaimed the following:
The "proper" method is to avoid Python and make suitable configuration changes to the R-Pi boot...
formatting link

No surprise there... All that statement does is create a Python datetime object/instance initialized to a particular date/time value -- and then throws it away.. Usage should be:
mydate = datetime.datetime(...)
to keep the created instance with the name "mydate". Of course, that still does nothing for setting a clock module at the system level.
First recommendation -- forget the interactive shell... It is really just meant for testing snippets of code. If you really want to use Python for all this, write a script file that can be executed outside of the IDE.
Second -- study the Python Library Reference manual... I'd direct you to the section on subprocess.popen() (or for quick&dirty, the deprecated os.execute()).
At least the default R-Pi setup gives the "pi" account sudo privilege without needing to enter a password (Plain Debian and Beaglebone require the user account password to perform sudo -- this helps prevent someone walking by a logged in machine from randomly doing "sudo something-malicious" as they would need to know the password of the logged in user). If it did, you might have to study the "expect" module.
--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber
Not from the Thonny REPL.
Yes. See
formatting link
plus the replies to that and other answers.
Reply to
A. Dumas
Dennis,
After a few hours I realized that that might be the case. Would have expected at least a warning for that creating-but-not-using-it though.
And thats what I'm doing, as a python user of less than a week (have been programming for a number of years though). :-)
And that makes me feel like I'm back in my BASIC days, having to shell for all the interesting stuff ...
I also found a solution using "subprocess.call()"
formatting link
although I had to combine all the arguments to a single one (why?) it does seem to work. Its just that I could not believe that I would have to do it that way.
:-) I have the Pi open to be able to connect stuff to its GPIO. If someone wanted to do something malicious than just going over them with a coin (short-circuiting them) would likely destroy a few - instead of just having to re-install. Or even just "by accident" spilling some liquid onto it would be enough.
But ... Really no method to do it from within python (even if I would have to use "sudo python3 {script.py}")? Bizarre.
Regards, Rudy Wieser
Reply to
R.Wieser
Alexandre,
And not from within "python3 script.py" either.
Yep, while googeling I found that one too. Its from eight years back though, which 1) made me think it could be old, not compatible to v3 code and 2) made me hope that python had, in the mean time, added the functionality.
I just ran the _linux_set_time() code by tMC (Sep 6 '12 at 4:12). It doesn't throw errors when run in user mode, and does seem to work when sudo-ed. I'll have to study that code to see how it works.
Thanks for the pointer.
Regards, Rudy Wieser
Reply to
R.Wieser
On Sat, 2 Nov 2019 20:15:21 +0100, "R.Wieser" declaimed the following:
Why bizarre?
Okay -- it appears the C runtime supports a settimeofday()... So using the Python ctypes library/module should permit you to access that function.
Python isn't really aimed at being a /systems/ language, but more an application/script language -- and user applications normally don't need access to functions that can change the system environment.
I presume
formatting link
""" time.clock_settime(clk_id, time: float)
Set the time of the specified clock clk_id. Currently, CLOCK_REALTIME is the only accepted value for clk_id.
Availability: Unix.
New in version 3.3. """ doesn't affect the desired clock. (I don't know how often ntp does updates)
pi@rpi3bplus-1:~$ sudo python3 Python 3.7.3 (default, Apr 3 2019, 05:39:12) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information.
1572743513.3025973
1572743525.0147276
1572743533.9680963
'Sat Nov 2 21:12:42 2019'
... print(time.ctime()) ... time.clock_settime(time.CLOCK_REALTIME, time.clock_gettime(time.CLOCK_REALTIME) + (5 * 60.0)) ... print(time.ctime()) ...
Sat Nov 2 21:14:48 2019 Sat Nov 2 21:19:48 2019
pi@rpi3bplus-1:~$ date Sat 02 Nov 2019 09:15:01 PM EDT pi@rpi3bplus-1:~$
The program saw a 5-minute time jump, but by the time I exited and checked from the command line it was back to normal.
--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber
Dennis,
A very basic property of the OS (which you can /read/ from in a slew of ways), but no way to set it.
I can understand, in a multi-user machine, why not just anybody should be able to muck around with it, but disallowing even root users to easily change it ...
Yep, that (ctypes library/module) is something I need to take a better look at. I must say that I rather like it that python has such an "you can call anything you like, just use this interface" method.
True.
Than again, I'm not just a linux user. I've bought a Raspberry for a reason (so many GPIO pins, my preciousss). :-)
I don't know either. But its certainly something to pursue. Although ... having to convert a set of simple date & time values into a datetime float might be its own challenge ...
In my case I often run my Pi disconnected from the 'web. Hence my wish to be able to update the system clock from an RTC. I've currently got no problem with, when connected to the 'web, the NTP service overruling it.
Regards, Rudy Wieser
Reply to
R.Wieser
On Sun, 3 Nov 2019 08:20:59 +0100, "R.Wieser" declaimed the following:
Well, applications often need the current time for reporting purposes -- but said time should rarely need to be set, and all OSs that I know of provide command line utilities for setting it.
Thing is -- it is the OS that is multi-user, even if you consider it a single-user machine. There may things running that rely upon the clock never going backwards (note that going to/from daylight savings time is NOT moving the clock itself -- the clock runs UTC and computes the shift based upon environment settings). Not to mention that the clock is actually counting seconds since some date in 1970.
If it's GPIO pins you crave -- take a look at a Beaglebone Black (which also has analog I/O). Granted, that single core 1GHz processor looks wimpy these days but... it does have a pair of PRU processors (basically 200MHz micro-controllers) for realtime work. Runs Debian so no real difference from R-Pi "Raspbian".
Well, as hinted above, that float is just seconds from 1970.
1572804690.0
'Sun Nov 3 13:11:01 2019'
1572804665.9523017
(Confusing in that inputs are Y M D H M S, but also weekday and julian day number -- I set both to 0; the last 0 is DST-no) What may be a concern is that expects the time as /local/ time, using the environment
Or, staying just in datetime to get the float value (still using time.* for comparison)
1572806325.0
1572806049.7643929
'Sun Nov 3 13:34:16 2019'
--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber
Dennis,
... unless you have a small computer which does not have its own RTC, but just depends on an always-available connection to "thar intawebz" - which it isn't.
Than I hope that the Pi's internal clock never runs fast. Otherwise the first re-syncing with an ntp server would cause a problem. Ofcourse, making the clock jump forward as a result of that re-syncing might not be good for something-or-another either. :-p
Does an atmel mega32 (and family) also count ?
Yup, the famous "epoch". But I would really like to see your calculation to convert the year, month, day, hour, minute and second values into such a float. You know the joke about "and than you have two problems" ? That also seems to be true for home-made date/time functions.
Regards, Rudy Wieser
Reply to
R.Wieser
He showed you, it's the mktime() method.
Reply to
A. Dumas
Dennis,
My apologies. As Alexandre pointed out to me, you've already shown how you're doing that using the " time.mktime()" method.
Regards, Rudy Wieser
Reply to
R.Wieser
There is a separate monotonic clock which doesn?t jump discontinuously (forwards or backwards). The wall-clock time may have much worse behavior.
See ?man clock_getttime? for the available clocks under Linux.
It counts non-leap secods since 1970.
--
https://www.greenend.org.uk/rjk/
Reply to
Richard Kettlewell
Sorry, clock_gettime.
--
https://www.greenend.org.uk/rjk/
Reply to
Richard Kettlewell
On Sun, 3 Nov 2019 21:10:56 +0100, "R.Wieser" declaimed the following:
I presumed you wanted a regular OS on the unit. The Atmel chips fall into the no-OS* microcontroller class rather than OS-laden microcomputer class. The Arduino Due would let you stay with the ARM instruction set. Or maybe a TIVA C123#
formatting link
which has an ARM m4 with floating point -- and way too many timers (6 64-bit and 6 32-bit -- each of which can be split into two half-width timers). Four 10-pin headers. If you need more pins, the TIVA C1294 (or the 129E -- hardware encryption version) with 8 10-pin headers (but only 8 32-bit timers) and on-board Ethernet. They can be programmed using TI-RTOS.
* Well, the larger ones might support using FreeRTOS, though that's not what many would consider an OS per se.
# Interesting thing -- there are actually two identical processor chips on that board. One if for you to program, the other one runs the flash programmer and debug interface.
Well -- I did show what the Python 3.x datetime module contained for that...
Ignoring leap-second adjustments, I'd probably steal a program from my HP calculators (I misplaced the book documenting the algorithm) that converts calendar date to julian date, do a difference against the infamous epoch, and then multiply the result by 86000 to convert to seconds. (I suspect some unicode characters won't come through)
IF OVER 3 < THEN 3 ROLLD 12 + SWAP 1 - ELSE SWAP 3 ROLL END ? m y
IF t 1582.1015 ? THEN DROP y 100 / IP DUP NEG 2 + SWAP 4 / IP + END 365.25 y * IF y 0 < THEN .75 - END IP m 1 + 30.6001 * IP + + + 1720994.5 +
--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber
Dennis,
Well, I bought a raspberry pi because I wanted, after having worked with such no-OS controllers, to know how working with it feels.
You did, and I missed it. My bad.
[snip code]
Ehrrm... I think I would need to study its language tobe able to understand what it actually does ... But thanks nonetheless. :-)
Regards, Rudy Wieser
Reply to
R.Wieser
On Mon, 4 Nov 2019 17:47:13 +0100, "R.Wieser" declaimed the following:
I really need to do something with all of mine... I've got a few BASIC Stamps (2, 2p, and I think a 2px -- expensive things for the little capability). Arduino Uno, Mega, Esplora, Due. Scattering of loose PIC (and programming boards for them). A few Propeller boards (weird chips -- 8 lockstep cores with round robin access to external memory and NO interrupts; one is expected to assign a core to polling I/O pins to emulate interrupts. Normal mode is to have a P-BASIC interpreter loaded into the core RAM interpreting instructions from external memory). 2 each TIVA 123, 1294, 129E. Five assorted R-Pis (3B, 2x 3B+, 4B 2G and 4G). Two Beaglebone Blacks and one Beaglebone AI
Doesn't help that (at least in my client) the right-arrow and the greater-than-or-equal characters show as ?
HP reverse polish language; stack based calculator. Just the start (using -> for right arrow)
Take first item from stack and assign to "t" Load "t", take IntegerPart Load "t", ABSolute value, take FractionalPart, multiply by 100 DUPlicate, take IntegerPart, SWAP, take FractionalPart, multiply by 100
It may help to know that the input ("t") is
YYYY.MMDDddd
so that first pulls the YYYY (IP), then takes the .MMDDddd (FP), shifts left to get MM.DDddd, duplicates this, then pulls the MM (IP), swaps with the duplicated value, takes the .DDddd, multiplies by 100 to get DD.ddd -- leaving the stack with
YYYY MM DD.ddd
--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.