Data Wrangling
Importing Data Select, Drop & Rename Filter, Sort & Sample Add Columns Cleaning Data Dates & Time Join Data Aggregate & Transform
Data Analysis
Exploring Data Plotting Continuous Variables Plotting Discrete Variables
Machine Learning
Data Preparation Linear Models
Other Tutorials & Content
Learn Python for Data Science Learn Alteryx Blog



Pandas Dates & Time

Today

Create a dataframe column containing the current date:

import datetime as dt
orders['today'] = pd.to_datetime(dt.date.today())

Now

Create a dataframe column containing the current date and time:

orders['now'] = dt.datetime.now()

Date

Create a dataframe column containing the date 2020-02-01:

orders['date'] = dt.datetime(2020, 2, 1)

Pandas dt (Year, Month, Day, Hour etc)

Extract date and time features from the "order_date" datetime column in Pandas dataframe :

orders['year'] = orders['Order_Date'].dt.year
orders['qtr'] = orders['Order_Date'].dt.quarter
orders['month'] = orders['Order_Date'].dt.month
orders['week'] = orders['Order_Date'].dt.week
orders['day'] = orders['Order_Date'].dt.day
orders['weekday'] = orders['Order_Date'].dt.weekday
orders['hour'] = orders['Order_Date'].dt.hour
orders['minute'] = orders['Order_Date'].dt.minute

Weekend

Create a dataframe column indicating if the date in the "order_date" column occured at the weekend:

orders['weekend'] = orders['weekday'].apply(lambda x: 1 if x == 5 or x == 6 else 0)

Days Between Dates

Create a dataframe column containing the number of days between the dates in the "order_date" and "today" columns:

orders['days_since_order'] = (orders['today'] - orders['Order_Date']).dt.days

Dates Before and After

Create two dataframe columns containing the dates 7 days after and 7 days before the date in the "order_date" column:

orders['week_after_order'] = orders['Order_Date'] + dt.timedelta(days=7)
orders['week_before_order'] = orders['Order_Date'] - dt.timedelta(days=7)