Skip to content

Instantly share code, notes, and snippets.

@TIBTHINK
Last active October 11, 2024 00:20
Show Gist options
  • Save TIBTHINK/3958e5e46f6213f7d61407b598314697 to your computer and use it in GitHub Desktop.
Save TIBTHINK/3958e5e46f6213f7d61407b598314697 to your computer and use it in GitHub Desktop.
spotify artist time calculator
# you need to get a spotify dev account
# you also need to install spotipy using this command
# pip install spotipy
# put your client id and client secret where its labeled
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import re
# Spotify API credentials
client_id = 'your_client_id'
client_secret = 'your_client_secret'
# Authenticate with the Spotify API
auth_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(auth_manager=auth_manager)
def get_artist_id_from_url(url):
# Extract the artist's Spotify ID from the URL
pattern = r'artist/([a-zA-Z0-9]+)'
match = re.search(pattern, url)
if match:
return match.group(1)
else:
raise ValueError("Invalid Spotify artist URL")
def get_artist_albums(artist_id):
albums = []
results = sp.artist_albums(artist_id, album_type='album')
albums.extend(results['items'])
while results['next']:
results = sp.next(results)
albums.extend(results['items'])
return albums
def get_album_tracks(album_id):
tracks = []
results = sp.album_tracks(album_id)
tracks.extend(results['items'])
while results['next']:
results = sp.next(results)
tracks.extend(results['items'])
return tracks
def calculate_total_duration(artist_url):
# Get the artist's ID from the provided URL
artist_id = get_artist_id_from_url(artist_url)
# Fetch all albums from the artist
albums = get_artist_albums(artist_id)
total_duration_ms = 0
# Loop through all albums and get tracks
for album in albums:
album_tracks = get_album_tracks(album['id'])
# Sum the duration of each track
for track in album_tracks:
total_duration_ms += track['duration_ms']
# Convert the total duration from milliseconds to hours, minutes, and seconds
total_seconds = total_duration_ms // 1000
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
return hours, minutes, seconds
if __name__ == '__main__':
# Input the artist's Spotify URL
artist_url = input("Enter the Spotify URL of the artist: ")
try:
hours, minutes, seconds = calculate_total_duration(artist_url)
print(f"Total time to listen to all tracks: {hours} hours, {minutes} minutes, {seconds} seconds")
except ValueError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment