0

I need to set the date and time of my raspberry pi with a php script. After some research I use a php script to call a python script. My datetime.php :

$date = '2015-09-05'; 

$output = shell_exec('/usr/bin/python/home/pi/datalogger/modules/sys/write_date.py ' . $date);

echo $output;

os.system("sudo date -s "+"'"+date_object+"'")

write_date.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from datetime import datetime

def main():
    date=sys.argv[1]
    time='22:04'
    print(date) #for debug

    string_date=date+' '+time+':00'
    date_object2=datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S")
    date_object=date_object2.strftime("%a %b %d %H:%M:%S"+" UTC "+"%Y")
    os.system("sudo date -s "+"'"+date_object+"'")

if __name__ == '__main__':  
    main()

When I refresh my datetime.php I got my date print, so the script works... the problem is that my date is not update. But if I run write_date.py my command line I can update the datetime of raspberry.

1 Answers1

0

An example of setting the date, via PHP, on a Linux based system (E.G. Raspberry Pi):

<?php
date_default_timezone_set('UTC');
$dt = date("D M j G:i:s T Y", strtotime("2015-09-05 22:04"));
$output = shell_exec('sudo date -s "$dt"');
?>

Also strptime() and strftime() exist in PHP:

http://php.net/manual/en/function.strptime.php

http://php.net/manual/en/function.strftime.php

Digging a little deeper, you may need to allow your Web Server to execute /bin/date via an adjustment to /etc/sudoers file. Can add:

apache <hostname> = (root) NOPASSWD: /bin/date

Confirm the <hostname> by running cat /etc/hostname. I suspect it is raspberry or raspberrypi. Change it to fit your device.

To then run, we make one minor change to the script before:

$output = shell_exec('sudo /bin/date -s "$dt"');

That should do it. Found this info here: https://unix.stackexchange.com/questions/44865/change-server-date-using-php

Community
  • 1
  • 1
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • Twisty, I've tried but the date fo my raspberry don't change. Should I need to "active some sudo permissions"? – Daniel Correia Oct 06 '15 at 00:04
  • I suspect so. Just to confirm, the PHP page is running on the RPi, correct? If so the apache user or www-data may need permission to a specific location to run date. – Twisty Oct 06 '15 at 03:28
  • This will help with the permissions: http://unix.stackexchange.com/questions/44865/change-server-date-using-php – Twisty Oct 06 '15 at 03:40