I want to replace the following characters tmp from between the /tmp/ to the current date from this string /tmp/tmpy2919ufy.
The output should be something like this /20200615/tmpy2919ufy
Could you please give some ideas as to how I might be able to do this?
Thanks!
1 Answer
You can simply do this with datetime
from datetime import datetime
string = "/tmp/tmpy2919ufy"
replace_string = datetime.today().strftime('%Y%m%d')
string = string.replace('tmp',replace_string,1)
#output >>> '/20200615/tmpy2919ufy'
2 Comments
FObersteiner
you should note that this only changes the string, not the directory name. also, you do not need
regex here. a simple .replace('tmp', replace_string, 1) will do.working-yoghurt-1995
Thanks a lot, it definetly helps! :)
datetime.now().strftime('%Y%m%d'), see the docs