#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read min read

DateTime Basics

Learn to work with dates and times in pandas

DateTime Basics

Why DateTime Matters

Dates come in many formats:

  • "2024-01-15"
  • "01/15/2024"
  • "January 15, 2024"
  • "15-Jan-24"

Pandas can understand all of them!

Convert Text to DateTime

code.py
import pandas as pd

df = pd.DataFrame({
    'Date': ['2024-01-15', '2024-02-20', '2024-03-10']
})

# Before conversion - it's text
print(df.dtypes)  # object

# Convert to datetime
df['Date'] = pd.to_datetime(df['Date'])

# After conversion - it's datetime
print(df.dtypes)  # datetime64

Handle Different Date Formats

code.py
# Pandas understands many formats automatically
df = pd.DataFrame({
    'Date': ['01/15/2024', '02-20-2024', 'March 10, 2024']
})

df['Date'] = pd.to_datetime(df['Date'])
print(df)

All converted correctly!

Specify Format (When Needed)

code.py
df = pd.DataFrame({
    'Date': ['15-01-2024', '20-02-2024']  # Day-Month-Year
})

# Tell pandas the format: %d=day, %m=month, %Y=year
df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y')
print(df)

Common Format Codes

CodeMeaningExample
%YYear (4 digit)2024
%yYear (2 digit)24
%mMonth (number)01
%dDay15
%BMonth nameJanuary
%bMonth shortJan
%HHour (24hr)14
%MMinute30
%SSecond45

Extract Date Parts

code.py
df = pd.DataFrame({
    'Date': pd.to_datetime(['2024-01-15', '2024-06-20', '2024-12-25'])
})

df['Year'] = df['Date'].dt.year
df['Month'] = df['Date'].dt.month
df['Day'] = df['Date'].dt.day
df['Weekday'] = df['Date'].dt.day_name()

print(df)

Output:

Date Year Month Day Weekday 0 2024-01-15 2024 1 15 Monday 1 2024-06-20 2024 6 20 Thursday 2 2024-12-25 2024 12 25 Wednesday

More Date Parts

code.py
df['Date'].dt.year        # 2024
df['Date'].dt.month       # 1, 2, 3...
df['Date'].dt.day         # 1, 2, 3...
df['Date'].dt.hour        # 0-23
df['Date'].dt.minute      # 0-59
df['Date'].dt.weekday     # 0=Monday, 6=Sunday
df['Date'].dt.day_name()  # 'Monday', 'Tuesday'...
df['Date'].dt.month_name()# 'January', 'February'...
df['Date'].dt.quarter     # 1, 2, 3, 4
df['Date'].dt.is_weekend  # True/False

Handle Bad Dates

code.py
df = pd.DataFrame({
    'Date': ['2024-01-15', 'bad date', '2024-03-10']
})

# errors='coerce' makes bad dates NaN
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
print(df)

Output:

Date 0 2024-01-15 1 NaT <- "Not a Time" (missing) 2 2024-03-10

Key Points

  • pd.to_datetime() converts text to date
  • Use format if auto-detection fails
  • .dt gives access to date parts
  • errors='coerce' handles bad dates
  • NaT = Not a Time (like NaN for dates)

What's Next?

Learn to do math with dates - add days, find differences, and more.

SkillsetMaster - AI, Web Development & Data Analytics Courses