Part 7

Times and dates

Date and time objects

The standard-library datetime module represents calendar values as objects rather than unrelated numbers or strings.

from datetime import datetime

start = datetime(2020, 6, 29)
print(start)
print(start.day, start.month, start.year)
Sample output

2020-06-29 00:00:00 29 6 2020

Date and time objects can be compared with the familiar comparison operators. Subtracting two datetime objects returns a timedelta, which describes an elapsed duration:

from datetime import datetime

start = datetime(2020, 6, 29)
end = datetime(2020, 7, 2)
difference = end - start
print(difference.days)
Sample output

3

A timedelta can also move a date forward or backward. The date library handles month ends, year ends and leap days:

from datetime import datetime, timedelta

day = datetime(2020, 2, 28)
print(day + timedelta(days=1))
print(day + timedelta(days=2))
Sample output

2020-02-29 00:00:00 2020-03-01 00:00:00

Loading

Formatting and parsing dates

strftime formats a date for display, while strptime parses a string according to a documented format:

from datetime import datetime

day = datetime.strptime("29.6.2020", "%d.%m.%Y")
print(day.strftime("%d.%m.%Y"))
print(day.strftime("%Y-%m-%d"))
Sample output

29.06.2020 2020-06-29

Common format codes include %d for day, %m for month, %Y for a four-digit year, %H for hour and %M for minute. Prefer ISO-style YYYY-MM-DD strings in stored data: they are unambiguous and sort in calendar order.

Loading
You have reached the end of this section! Continue to the next section:

You can check your current points from the blue blob in the bottom-right corner of the page.