· 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# 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}")
16list_id = "7c65384a6d" # use this to set the list ID once you've figured it out. replace "7c65384a6d" with the ID of your list
17
18# Get the members within the list
19members = client.lists.members.all(list_id, get_all=True)
20# print(f"members: {members}") # this will print all the members in the list
21
22
23# Set a cutoff date to 2020-10-30, we'll use this to decide if the member should be removed from the list
24# You'll want to update this to the day before you imported all the contacts you want to remove
25cutoff_date = datetime.datetime(2020, 10, 30)
26
27
28# Loop through each member and delete the member from the list if the member was added after the cutoff date
29for member in members['members']:
30 # this code will run once for each member
31 print()
32 member_id = member['id']
33 timestamp = member['timestamp_opt']
34 # 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
35 # was added before or after the cut off date
36 timestamp_in_datetime = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S%z').replace(tzinfo=None)
37 email = member['email_address']
38
39 print(f"member id: {member_id}")
40 print(f"email: {email}")
41 print(f"date added: {timestamp}")
42 if timestamp_in_datetime > cutoff_date:
43 # This code will only run if the member was added after the cutoff date
44 print(f'Member {email} was added after the cutoff date')
45 # 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
46 # client.lists.members.delete(list_id=list_id, subscriber_hash=member_id)
47 else:
48 # This code runs if the member was added before the cutoff date
49 # no need to do anything here
50 print(f'Member {email} was added before the cutoff date')