Skip to content

Python API

from lastfm import LastFM

with LastFM(api_key="...") as client:
    for track in client.recent_tracks("hp0404", start_date="2021-08-21"):
        print(track["datetime"], track["artist"], "-", track["track"])

    for track in client.loved_tracks("hp0404"):
        print(track["artist"], "-", track["track"])

Both methods are generators that paginate through the Last.fm API for you, politely (rate-limited, with retries on transient errors). Tracks come newest first, which makes client-side filtering cheap — stop iterating once you are past the date you care about:

loved_2026 = []
for track in client.loved_tracks("hp0404"):
    if track["datetime"] < "2026-01-01":
        break
    loved_2026.append(track)

Reference

Read-only client for a user's Last.fm listening history.

Parameters:

Name Type Description Default
api_key str

Last.fm API key (https://www.last.fm/api/account/create).

required
rate_limit float

Seconds to sleep between page requests, by default 0.25.

0.25
session Session

Pre-configured HTTP session; mainly useful for testing. When omitted, a session with retries on transient errors is created.

None

Examples:

>>> with LastFM(api_key="...") as client:
...     for track in client.recent_tracks("hp0404"):
...         print(track["artist"], "-", track["track"])

recent_tracks(user, *, start_date=None, end_date=None)

Yield every scrobble of user, newest first.

Parameters:

Name Type Description Default
user str

Last.fm username.

required
start_date str or date or datetime

Restrict the export to a date range. Strings use the YYYY-MM-DD format; dates are interpreted as UTC.

None
end_date str or date or datetime

Restrict the export to a date range. Strings use the YYYY-MM-DD format; dates are interpreted as UTC.

None

Yields:

Type Description
dict

One row per scrobble with keys uts_timestamp, datetime, artist, artist_mbid, album, album_mbid, track, track_mbid, and url. The currently playing track (which has no timestamp yet) is skipped.

loved_tracks(user)

Yield every track user has loved, newest first.

Parameters:

Name Type Description Default
user str

Last.fm username.

required

Yields:

Type Description
dict

One row per loved track with keys uts_timestamp (when the track was loved), datetime, artist, artist_mbid, track, track_mbid, and url.

scrobble_count(user, *, start_date=None, end_date=None)

Return the number of scrobbles user has in the date range.

loved_count(user)

Return the number of tracks user has loved.

Bases: Exception

Raised when the Last.fm API returns an error payload.