Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krisbolton/a6634083f53b02c0a562dd674c8f49fb to your computer and use it in GitHub Desktop.
Save krisbolton/a6634083f53b02c0a562dd674c8f49fb to your computer and use it in GitHub Desktop.
Count the number of unique days in a datetime dataframe column

Problem

I want to count the number of unqiue days within a pandas dataframe column contianing datatime dtypes. The use-case is Twitter data from TWINT, "How many days has a user tweeted within the collected time period?". The code below assumes the datetime column is called date.

Solution

You must first convert the datetime column using pd.to_datetime and use pandas dt to access the date portion of the date time. This can then be used by the unique() and len() function to count unique occurances.

df['date_only'] = pd.to_datetime(df['date'])
date_only = df['date_only'].dt.date
num_days = len(date_only.unique())
num_days
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment