0

I am writing a python code to change the date in linux system to today-1 (dynamically). I tried various combinations but, yet I am not able to succeed. I searched and I found a close proximity to my scenario in this question .

I am able to change the date if I execute the command with static value say:

date --set="$(date +'2013%m%d %H:%M')"

However, I don't want to specify hardcoded value for year i.e., 2013. Instead i want to specify something like "%y-1" i.e.,

date --set="$(date +'%y-1%m%d %H:%M')"

If I run the above command I get the following error

[root@ramesh ~]$ date --set="$(date +'%y-1%m%d %H:%M')"
date: invalid date `14-11016 13:05'
Community
  • 1
  • 1
Ramesh A
  • 21
  • 3
  • Related: http://stackoverflow.com/questions/12081310/python-module-to-change-system-date-and-time – Robᵩ Oct 16 '14 at 18:41

2 Answers2

2

Thanks for your answer. I did not try your approach though, reason being it has to be once again dealt with formatting issues when working with arithmetic operations incase if you want to.

So, I figured out a much simpler and generalized approach

Fetch the previous_year value with this command

date --date='1 years ago'

This gives the previous year date. Now this can be used in the python program to update the system in the following way

"date --set=$(date +'%%y%%m%s %%H:%%M') % previous_year"

This method has few advantages like

  1. I can apply this method for day and month as well like "1 days ago", "1 month ago" along with +%d, +%m, +%y values.

    e.g., date --date='1 years ago' +%y

  2. I don't have to worry about the date and month arithmetic calculation logics

Community
  • 1
  • 1
Ramesh A
  • 21
  • 3
0

date will interpret the %y-1 literally has you showed. What you need is to retrieve the current year, subtract 1 and use this value as the new year. To get the current_year - 1 you can do:

previous_year=$((`date +'%y'`-1))
echo $previous_year 
>>> 13

Now you just need to use this variable to set the new date.

El Bert
  • 2,958
  • 1
  • 28
  • 36