Created
February 2, 2020 10:56
-
-
Save cgarz/6ca49e58a809f3295bac965b8c1bfdd1 to your computer and use it in GitHub Desktop.
Pretty print all saved tracks and associated info from a Spotify account using Spotipy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import spotipy | |
import dateutil.parser | |
USERNAME = 'XXX' | |
CLIENT_ID = 'XXX' | |
CLIENT_SECRET = 'XXX' | |
REDIRECT_URI = 'http://localhost/' | |
SCOPE = 'user-library-read' | |
LIMIT = 50 | |
TIME_FORMAT = '%Y-%m-%d %H:%M:%S UTC' | |
def convert_ms(ms): | |
s = ms / 1000 | |
m, s = divmod(s, 60) | |
h, m = divmod(m, 60) | |
s = round(s, 2) | |
m = int(m) | |
h = int(h) | |
formatted = '' | |
m_format = '{:d}:' | |
if h: | |
formatted += '{:d}:'.format(h) | |
m_format = '{:02d}:' | |
formatted += m_format.format(m) | |
formatted += '{:05.2f}'.format(s) | |
return formatted | |
def main(): | |
token = spotipy.util.prompt_for_user_token( | |
USERNAME, SCOPE, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI | |
) | |
spotify = spotipy.Spotify(auth=token) | |
results = spotify.current_user_saved_tracks(limit=LIMIT) | |
items = results['items'] | |
while results['next']: | |
results = spotify.next(results) | |
items += results['items'] | |
for idx, item in enumerate(items, start=1): | |
print('Added at.:', dateutil.parser.isoparse(item['added_at']).strftime(TIME_FORMAT)) | |
print('Title....:', item['track']['name']) | |
if len(item['track']['artists']) > 1: | |
print('Artists..:', ', '.join([artist['name'] for artist in item['track']['artists']])) | |
else: | |
print('Artist...:', item['track']['artists'][0]['name']) | |
print('Album....:', item['track']['album']['name']) | |
print('Duration.:', convert_ms(item['track']['duration_ms'])) | |
print('URL......:', item['track']['external_urls']['spotify']) | |
if idx < len(items): | |
print() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment