Mathew K Analytics

Lesson 31 · Python for Data Science

Date and Time Basics in Python: Essential Skills for Data Science Beginners

Welcome! Today you will learn how to work with dates and times in Python. Dates and times are important for many real-world programs, like logging events,…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Python Date and Time Basics#

Welcome! Today you will learn how to work with dates and times in Python.

Dates and times are important for many real-world programs, like logging events, scheduling reminders, or showing a clock. You will see how Python helps make sense of days, months, seconds and even how you can calculate with time.

Why should you care about dates and times?#

  • Applications like calendars, alarms, and logs all use dates.
  • Working with birthdays, deadlines, or tracking habit streaks needs date math.
  • Time zones and clocks are important in global programs.
# Import the datetime module to work with dates and times
import datetime
# Get today's date using datetime
today = datetime.date.today()
print('Today is:', today)
Today is: 2025-08-14
# Create a specific date: for example, a birthday
birthday = datetime.date(2000, 6, 15)
print('Birthday:', birthday)
Birthday: 2000-06-15
# Calculate the number of days between today and a date
days_since = today - birthday
print('Days since birthday:', days_since.days)
Days since birthday: 9191
# Get the current time with datetime.datetime.now()
now = datetime.datetime.now()
print('Current time:', now)
Current time: 2025-08-14 12:51:57.152299

Breaking down a datetime object#

  • You can get the year, month, day, hour, minute, and second separate from a datetime.
  • This helps you show only what you need.
# Extract parts of the date and time
print('Year:', now.year)
print('Month:', now.month)
print('Day:', now.day)
print('Hour:', now.hour)
print('Minute:', now.minute)
print('Second:', now.second)
Year: 2025
Month: 8
Day: 14
Hour: 12
Minute: 51
Second: 57

Formatting dates and times#

You can change how a date or time looks. It can be written with slashes, spaces, or words, depending on what you want. Python uses the strftime function to format things.

# Format the date as 'Month Day, Year'
formatted = now.strftime('%B %d, %Y')
print('Pretty format:', formatted)
Pretty format: August 14, 2025
# Format the time as hour:minute AM/PM
formatted_time = now.strftime('%I:%M %p')
print('Time:', formatted_time)
Time: 12:51 PM

Getting user input for a date#

You can let users type a date, and then work with it in your code. Use the input() function and the datetime.strptime function to convert a string into a date.

# Ask the user for a date (in YYYY-MM-DD format)
user_input = input('Enter a date (YYYY-MM-DD): ')
user_date = datetime.datetime.strptime(user_input, '%Y-%m-%d').date()
print('You entered:', user_date)
You entered: 2023-12-25
 
# Handle wrong input with a try...except block
try:
    user_input = input('Enter another date (YYYY-MM-DD): ')
    user_date = datetime.datetime.strptime(user_input, '%Y-%m-%d').date()
    print('You typed:', user_date)
except ValueError:
    print('Oops! That was not the right format. Please try again.')
    
Oops! That was not the right format. Please try again.
 
# Adding or subtracting days with timedelta
one_week = datetime.timedelta(days=7)
future = today + one_week
print('One week from today:', future)
One week from today: 2025-08-21
# How many days until New Year?
new_year = datetime.date(today.year + 1, 1, 1)
days_left = (new_year - today).days
print('Days until New Year:', days_left)
Days until New Year: 140
# List of important dates
important = [
    datetime.date(2024, 1, 1),
    datetime.date(2024, 12, 25),
    datetime.date(2024, 7, 4)
]
for day in important:
    print('Important:', day.strftime('%B %d, %Y'))
    
Important: January 01, 2024
Important: December 25, 2024
Important: July 04, 2024
# Find all dates after today
future_dates = [d for d in important if d > today]
print('Upcoming:', future_dates)
Upcoming: []
# Sorting a list of dates
mixed = [
    datetime.date(2023, 3, 12),
    datetime.date(2025, 8, 9),
    datetime.date(2022, 11, 5)]
mixed.sort()
print('Dates sorted:', mixed)
Dates sorted: [datetime.date(2022, 11, 5), datetime.date(2023, 3, 12), datetime.date(2025, 8, 9)]
# Mini-project: Reminder for birthdays coming soon
friends = [
    ("Alice", datetime.date(2024, 8, 10)),
    ("Bob", datetime.date(2024, 9, 2)),
    ("Carmen", datetime.date(2024, 6, 20))
]
print('Birthdays in the next 30 days:')
for name, bday in friends:
    if 0 < (bday - today).days <= 30:
        print(f"{name}: {bday.strftime('%B %d')}")
        
Birthdays in the next 30 days:
# Mini-project part 2: Adding your own birthday using input
your_name = input('Your name: ')
your_birthday = input('Your birthday (YYYY-MM-DD): ')
your_date = datetime.datetime.strptime(your_birthday, '%Y-%m-%d').date()
if 0 < (your_date - today).days <= 30:
    print('You have a birthday coming up soon!')
else:
    print('No birthday soon, but it will come around next year.')
    
No birthday soon, but it will come around next year.
 

Common mistakes with dates and times#

  • Forgetting to import the datetime module.
  • Using the wrong format for input() or strftime/strptime.
  • Mixing up date and datetime types.
  • Not handling time zones (for now, keep it simple and use local time).
  • Assuming date subtraction always gives a number (it gives a timedelta object!).
# Tip: Get current date and time in one line
from datetime import datetime
now = datetime.now()
print(now)
2025-08-14 13:01:47.377159

Recap: What did you learn?#

  • How to get and create dates and times in Python.
  • How to format them for friendly output.
  • Doing math with dates for reminders and counters.
  • Making lists and loops for tracking many dates.
  • Handling user input and errors.

These are skills you can use in real apps!

Thanks for learning with me today!

If you enjoyed this lesson, remember to:

  • Like the video
  • Leave a comment with your favorite date trick
  • Subscribe for more coding walkthroughs
  • Share this with your friends!

Happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.