Home > OS >  manage variables in python for loop
manage variables in python for loop

Time:11-10

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:

  1. If I understand correctly, your first question is how to retrieve a variable value by its name. I show you two ways.

    • data structure dict

      There are two intrinsic directories recording all global/local variables from their names to values in the current scope, which can be obtained via globals() and locals() respectively. Therefore globals()['job1_started'] or locals()['job1_started'] will give you the value of global variable job1_started or the local one.

    • built-in function eval

      eval evaluates an expression string in the given namespace (default local namespace). Therefore, eval('job1_started') is equivalent to locals()['job1_started']. But you should be very careful when using eval because the string could be a dangerous expression, e.g., "__import__('os').system('rm -rf something_important')".

  2. The second question is how to add 1 day to a date string. You can achieve this with datetime module.

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}')
  • Related