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!
Asked
Active
Viewed 954 times
1

working-yoghurt-1995
- 99
- 6
-
have a look at [this](https://stackoverflow.com/a/62154151/10197418) - is that what you need? the current date as string is simply `datetime.now().strftime('%Y%m%d')`, see the [docs](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) – FObersteiner Jun 15 '20 at 11:37
1 Answers
1
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'

Sarthak Kumar
- 304
- 5
- 16
-
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. – FObersteiner Jun 15 '20 at 11:46
-