In this Python Tutorial of learning python in 30 days , we will be learning how to use the datetime module in python and how to use datetime python to extract and create other variable such as day of week, weekday, name of the day etc.
Below are the topics covered in this video:
The time module
Built-in functions
Examples
The datetime module
Built-in functions
combine date and time in python
Examples
we will see how to use date and time in python to create new variables as a part of feature engineering python.
Python gives you three classes for working with dates and times: the date, time and datetime classes. All three classes are found in the datetime module. In this lesson we will cover the main uses of all three classes.
Check out full feature engineering python playlist :
import datetime
import pandas as pd
import numpy as np
date = pd.Series(pd.date_range('01-01-2020', periods=1000, freq="H"))
data = pd.DataFrame(dict(Pay_date= pd.to_datetime(date)))
data.head()
# Extract Hour , Minute and Second
data['Pay_Hour'] = data['Pay_date'].dt.hour
data['Pay_Minute'] = data['Pay_date'].dt.minute
data['Pay_Second'] = data['Pay_date'].dt.second
data.head()
# Get the Week from the date
data['Week'] = data['Pay_date'].dt.isocalendar().week
data
data['Week'].unique()
# lets get the Month
data['Month'] = data['Pay_date'].dt.month
data.head()
data['Month'].unique()
# How to Extract the quarter from date
data['Quarter'] = data['Pay_date'].dt.quarter
data.head()
# How to extract semester from date
data['Semester'] = np.where(data['Quarter'].isin([1,2]), 1, 2)
data.head()
# Extract year
data['Payment_Year'] = data['Pay_date'].dt.year
data.head()
# Extract day of week
data['day_of_week'] = data['Pay_date'].dt.dayofweek
data.head()
# Extract the name of the day
data['weekday_name'] = data['Pay_date'].dt.day_name()
data.head()
# Extract Time elapsed between dates
date1 = pd.to_datetime('2020-01-01')
date2 = pd.to_datetime('2020-01-30')
elapsedtime = date2 - date1
elapsedtime
# Calcualate difference to a given date from today
(datetime.datetime.today() - date1)
Related tags:
datetime python
datetime module python
python programming
python tutorial for brginners