DEV Community

Cover image for Working with Time: Python’s Date and Datetime Essentials
Mary Nyandia
Mary Nyandia

Posted on

Working with Time: Python’s Date and Datetime Essentials

Getting Today’s Date
The date.today() function gives the current date, useful for logging or scheduling.

from datetime import date
today = date.today()
print(today)

Enter fullscreen mode Exit fullscreen mode

Creating Specific Dates
You can create any date by specifying year, month, and day, which is helpful for birthdays or deadlines.

birthday = date(2000, 5, 15)
print(birthday)

Enter fullscreen mode Exit fullscreen mode

Calculating Differences
Subtracting two dates gives a timedelta, allowing you to measure durations in days.

age_days = today - birthday
print("Days since birthday:", age_days.days)

Enter fullscreen mode Exit fullscreen mode

Current Date and Time
datetime.now() provides the exact current time, and strftime() formats it for display.

from datetime import datetime
now = datetime.now()
print("Now:", now)
print("Formatted:", now.strftime("%Y-%m-%d %H:%M:%S"))

Enter fullscreen mode Exit fullscreen mode

Adding Time
timedelta lets you add or subtract time, making it easy to calculate future or past dates.

from datetime import timedelta
future = now + timedelta(days=10)
print("In 10 days:", future)

Enter fullscreen mode Exit fullscreen mode

🎯 My Take
Python’s datetime module helps you:

  • Get today’s date and current time.
  • Create specific dates.
  • Calculate differences between dates.
  • Format timestamps for display.
  • Add or subtract time easily.

Dates and times are crucial for applications like scheduling, logging, and data analysis.

Top comments (0)