Dates and Times in Pandas


Often the best way to learn something is to just jump in and try it out. Go ahead and use the code below to practice working with dates and times in pandas. I created a project called Dates and Times in Pandas in Jupyter Notebook.

First we’ll manually create a very small DataFrame.

import pandas as pd
data = {'company': ['ABC Inc.', 'XYZ Corp.', 'Acme Ltd', 'Widget LLC'],
       'sales': ['1.286', '6.722', '3.320', '4.197'],
        'date_founded': ['2/25/2006 09:19:30', '5/17/2003 10:12:43', '3/7/2011 09:45:03', '11/2/2012 09:51:28']}
df = pd.DataFrame(data)
df

df.dtypes
company         object
sales           object
date_founded    object
dtype: object

You could also run info() to get the data types. Convert the column to datetime using pd.to_datetime().

# convert object to datetime
df['date_founded'] = pd.to_datetime(df['date_founded'])
df.dtypes

company                 object
sales                   object
date_founded    datetime64[ns]
dtype: object

Create new columns (features) based on the date founded.

# Create features for year, month, day, hour, minute
df['year'] = df['date_founded'].dt.year
df['month'] = df['date_founded'].dt.month
df['day'] = df['date_founded'].dt.day
df['hour'] = df['date_founded'].dt.hour
df['minute'] = df['date_founded'].dt.minute
df['second'] = df['date_founded'].dt.second
# Create 'day_name' col 
df['day_name'] = df['date_founded'].dt.day_name().str.lower()
# Create 'month_name' col
df['month_name'] = df['date_founded'].dt.strftime('%b').str.lower()
df

Click to Enlarge


Below we have created a month column in our DataFrame called df that contains the month name in a lower case sting of length three characters, based on the datetime column called my_datetime.

df['month'] = df['my_datetime'].dt.strftime('%b').str.lower()

Leave a Reply