below are input date values I have:
job1_started = '2020-01-01'
job1_end = '2021-01-01'
job2_started = '2022-01-01'
job2_end = '2023-01-01'
.
.
jobn_started = '2023-01-01'
jobn_end = '2023-01-01'
below is the input list I have:
list=['job1','job2',...... 'jobn']
I need to loop through all values in list and add 1 day to its corresponding date Values.
for date in list:
< logic needed>
below is the expected Output: (adding one day)
job1_started = '2020-01-02'
job1_end = '2021-01-02'
job2_started = '2022-01-02'
job2_end = '2023-01-02'
.
.
jobn_started = '2023-01-02'
jobn_end = '2023-01-02'
How can I do this?
CodePudding user response:
If I understand correctly, your first question is how to retrieve a variable value by its name. I show you two ways.
data structure
dictThere are two intrinsic directories recording all global/local variables from their names to values in the current scope, which can be obtained via
globals()andlocals()respectively. Thereforeglobals()['job1_started']orlocals()['job1_started']will give you the value of global variablejob1_startedor the local one.built-in function
evalevalevaluates an expression string in the given namespace (default local namespace). Therefore,eval('job1_started')is equivalent tolocals()['job1_started']. But you should be very careful when usingevalbecause the string could be a dangerous expression, e.g.,"__import__('os').system('rm -rf something_important')".
The second question is how to add 1 day to a date string. You can achieve this with
datetimemodule.- use
strptimeto convert string todatetime.datetimeobject, andstrftimefor the reverse - use
datetime.timedeltato update date
- use
Example
import datetime
job1_started = '2020-01-01'
job1_end = '2021-01-01'
jobs = ["job1"]
for job in jobs:
for suffix in ('_started', '_end'):
var_name = job suffix
date_str = locals()[var_name]
date = datetime.datetime.strptime(date_str, "%Y-%m-%d") # 2020-01-01 00:00:00
date_delta = datetime.timedelta(days=1)
date = date date_delta # 2020-01-02 00:00:00
date_str = datetime.datetime.strftime(date, "%Y-%m-%d") # '2020-01-02'
# update the variable at the local scope
locals()[var_name] = date_str
print(f'{var_name} = {date_str}')
