Is there a better way to set a system clock in Python (on a Linux system)

Chris Rebert clp2 at rebertia.com
Wed May 5 23:01:44 EDT 2010


On Wed, May 5, 2010 at 7:47 PM, J <dreadpiratejeff at gmail.com> wrote:
> Is there a better way to do this?

Yes:

from datetime import datetime, timedelta
> def SkewTime():
>    '''
>    Optional function. We can skew time by 1 hour if we'd like to see real sync
>    changes being enforced
>    '''
>    TIME_SKEW=1
>    logging.info('Time Skewing has been selected. Setting clock ahead 1 hour')
>    # Let's get our current time
    skewed = datetime.now() + timedelta(hours=TIME_SKEW)
>    # Now create new time string in the form MMDDhhmmYYYY for the date program
    date_time_str = skewed.strftime('%m%d%H%M%Y')
    logging.debug('New date string is: %s' % date_time_str)
>    logging.debug('Setting new system time/date')
    status = SilentCall('/bin/date %s' % date_time_str)
>    logging.info('Pre-sync time is: %s' % time.asctime())
>
> Anyway, what I'm wondering, is, while this works, is there a better
> way to do it than using part of the originally returned time_struct
> and injecting my own new hour argument (hr).

Use the datetime module roughly as shown. (Disclaimer: Code is untested).
Also, I'm not sure if your original code worked properly after 11PM;
my code definitely should.

> This just looks... well, big to me.  I tried passing only the things I
> really needed to time.strftime(), but apparently, that requires the
> full 9-tuple from time_struct, not just individual parts of it.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list