2

I'm trying to make a function to manually change the date/time on a Linux box, using subprocess.call to date --set= on the box. My issue is in trying to find a cleaner/more pythonic way of formatting everything together to go into the call.

The reason I did it this way is because the date command requires --set= followed by a string, and I couldn't figure out a way to do that in proper format within subprocess.call.

I know ideally I should just use ntpd but unfortunately this is my requirement right now. Any help is greatly appreciated.

def set_system_time(year, month, day, hour, minute, second):
    """Set system time, numeric value formatted as 'YYYY-MM-DD HH:MM:SS'"""
    datetime = '--set=' + str(year) + '-' + str(month) + '-' + str(day) \
        + ' ' + str(hour) + ':' + str(minute) + ':' + str(second)
    subprocess.call(['date', datetime])
waltermj
  • 23
  • 2
  • 2
    Use `strptime` and `strftime` from the `datetime` module. Your format string should look roughly like `fmt = '%Y-%m-%d %H:%M:%S'` This question has example usage: http://stackoverflow.com/q/14762518/553404 – YXD Feb 14 '14 at 17:13
  • 1
    You should use a different interface `def set_system_time(my_datetime)` and then `strftime`. There is a deleted answer here about this, I'm not sure why he deleted it as it is the best answer. – wim Feb 14 '14 at 17:49
  • strftime is a good way to go, but not with the existing set of parameters. If you get parameters like the question author asked (and not in terms of datetime library), it has no advantage over plain string formatting. – Ellioh Feb 14 '14 at 17:51

2 Answers2

2

Use string formatting:

datetime = '--set={}-{}-{} {}:{}:{}'.format(year, month, day, hour, minute, second)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

With variable number of arguments (shorter, but less readable since you can't see parameter names):

def set_system_time(*a):
    datetime = '--set=%d-%d-%d %02d:%02d:%02d' % a

With fixed number of arguments:

def set_system_time(year, month, day, hour, minute, second):
    datetime = '--set=%(year)d-%(month)d-%(day)d %(hour)02d:%(minute)02d:%(second)02d' % locals()
Ellioh
  • 5,162
  • 2
  • 20
  • 33