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,…
- CoursePython for Data Science
- Lesson31 of 38
- Video14 min
- FormatJupyter notebook · 22 code cells
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)
# Create a specific date: for example, a birthday
birthday = datetime.date(2000, 6, 15)
print('Birthday:', birthday)
# Calculate the number of days between today and a date
days_since = today - birthday
print('Days since birthday:', days_since.days)
# Get the current time with datetime.datetime.now()
now = datetime.datetime.now()
print('Current time:', now)
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)
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)
# Format the time as hour:minute AM/PM
formatted_time = now.strftime('%I:%M %p')
print('Time:', formatted_time)
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)
# 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.')
# Adding or subtracting days with timedelta
one_week = datetime.timedelta(days=7)
future = today + one_week
print('One week from today:', future)
# 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)
# 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'))
# Find all dates after today
future_dates = [d for d in important if d > today]
print('Upcoming:', future_dates)
# 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)
# 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')}")
# 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.')
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)
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.



