Course Outline (Part 28)

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.


1. datetime module

To work with dates, import the datetime module:

import datetime

2. datetime.now()

To get the current date and time, use the now() method:

import datetime

x = datetime.datetime.now()
print(x) # Output: 2026-06-12 14:30:45.123456

The date contains year, month, day, hour, minute, second, and microsecond.


3. Create date object

To create a date, we can use the datetime() class (constructor) of the datetime module.

The datetime() class requires three parameters to create a date: year, month, day.

import datetime

x = datetime.datetime(2020, 5, 17)
print(x) # Output: 2020-05-17 00:00:00

You can also pass in hours, minutes, seconds, and timezone, but they are optional.


4. date, time, datetime classes

The datetime module provides several main classes:

  • date: An idealized naive date, assuming the current Gregorian calendar. Attributes: year, month, day.
  • time: An idealized time, independent of any particular day. Attributes: hour, minute, second, microsecond.
  • datetime: A combination of a date and a time.
  • timedelta: A duration expressing the difference between two date, time, or datetime instances.

5. strftime() (format date as string)

The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string.

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B")) # 'June' (Full month name)
print(x.strftime("%Y")) # '2018' (Full Year)
print(x.strftime("%d/%m/%Y")) # '01/06/2018'

6. strptime() (parse string to date)

If you have a string representing a date, you can convert it back into a datetime object using strptime() (String Parse Time).

import datetime

date_string = "21 June, 2018"
date_object = datetime.datetime.strptime(date_string, "%d %B, %Y")

print(date_object) # 2018-06-21 00:00:00

7. Date arithmetic (timedelta)

You can perform arithmetic on dates using timedelta. This is extremely useful for finding out the date 30 days from now, or calculating a user’s age.

from datetime import datetime, timedelta

today = datetime.now()

# Adding 10 days
future_date = today + timedelta(days=10)
print(future_date)

# Subtracting 2 weeks
past_date = today - timedelta(weeks=2)
print(past_date)

# Difference between two dates
date1 = datetime(2023, 1, 1)
date2 = datetime(2023, 1, 15)
difference = date2 - date1

print(difference.days) # 14

Discussion

Loading comments...