· 5 years ago · Nov 01, 2020, 07:50 PM
1import datetime
2from mailchimp3 import MailChimp
3
4# lines that start with '#' do not run. you'll need to remove the '#' to make them run
5
6api_key = "put your API KEY here"
7username = "put your username here"
8
9client = MailChimp(mc_api=api_key, mc_user=username)
10
11# Get all the lists
12lists = client.lists.all(get_all=True, fields="lists.name,lists.id")
13
14# Use the first list since I only have one list, if you have multiple you'll have to use the next line to print the lists and figure out what the ID is for the list you want to target
15print(f"lists: {lists}") # use this to show all your lists so you can get the ID of the right list
16list_id = lists['lists'][0]['id']
17# list_id = "7c65384a6d" # use this to set the list ID once you've figured it out. replace "7c65384a6d" with the ID of your list
18
19# Get the members within the list
20members = client.lists.members.all(list_id, get_all=True)
21# print(f"members: {members}") # this will print all the members in the list
22
23
24# Set a cutoff date to 2020-10-30, we'll use this to decide if the member should be removed from the list
25# You'll want to update this to the day before you imported all the contacts you want to remove
26cutoff_date = datetime.datetime(2020, 10, 30)
27
28
29# Loop through each member and delete the member from the list if the member was added after the cutoff date
30for member in members['members']:
31 # this code will run once for each member
32 print()
33 member_id = member['id']
34 timestamp = member['timestamp_opt']
35 # this is to get both the cutoff date and the member timestamp in the same format so we can compare them to see if the member
36 # was added before or after the cut off date
37 timestamp_in_datetime = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
38 email = member['email_address']
39
40 print(f"member id: {member_id}")
41 print(f"email: {email}")
42 print(f"date added: {timestamp}")
43 if timestamp_in_datetime > cutoff_date:
44 # This code will only run if the member was added after the cutoff date
45 print(f'Member {email} was added after the cutoff date')
46 # The next line will remove the member from the list, only remove the '#' once you're seeing the 'Member <email> was added after the cutoff date' and the emails match up to the ones you want to delete
47 # client.lists.members.delete(list_id=list_id, subscriber_hash=member_id)
48 else:
49 # This code runs if the member was added before the cutoff date
50 # no need to do anything here
51 print(f'Member {email} was added before the cutoff date')