-3

I am totally beginner in python. I wrote the code which gave me the number below. In this number I have a year month and day in the one word string. I want to know how can I remove the days ( I mean two digits from the right):

20220612

20220819

20220926

I wrote the code which is like this:

temporary_data = {
                'year': year[i].text,
                'month':'',
                'imp/exp':'1',
                'commodities': commodities[i].text,
                'countries': countries[i].text,
                'quantities': quantities[i].text,
                'weights': weights[i].text }
            #-----------------------------------------------------
            temporary_data['year']=temporary_data['year'].replace('-', '')          #code for eleminating the - between year and month
            temporary_data['year']=temporary_data['year'][:-2]                      #code for eleminating the days number
            temporary_data['month']=temporary_data['year'][4:]
            tempor ary_data['year']=temporary_data['year'][:4] 
            #------------------------------------------------------
            if '—' in temporary_data['commodities']:
                    temporary_data['commodities'] = temporary_data['commodities'].replace(".", "")
                    temporary_data['commodities'] = temporary_data['commodities'].split(' —')[-2]
                    temporary_data['commodities']=temporary_data['commodities'][0:6]

after the code runs it should become to the below data:

2022,06

2022,08

2022,09

I don't know why it doesn't work!

Saeid Vaygani
  • 179
  • 1
  • 1
  • 8

3 Answers3

2

Let's say dct is your dictionary, and all values in the dictionary are strings (i.e., {key1: "20220615", key2: "20220616", ...}:

new_dct = {k: v[:-2] for k, v in dct.items()}
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1

Probably easiest way is use slicing, if they are strings.

>>> "20220214"[:-2]  # remove last two chars
'202202'

>>> "20220214"[:6]  # take first six chars
'202202'
ex4
  • 2,289
  • 1
  • 14
  • 21
0

That depends on type of the variable you are using.

For a str type it is quite easy, as you can use slicing:

number = "20220615"
number = number[:-2]

For an int type, you can use integer division by 100 in this case.

number = 20220615
number = number // 100

You need to provide more information

Blindschleiche
  • 271
  • 1
  • 7