Lesson 82 +10 XP

Dates

Dates

Python has no built-in date type, but the datetime module provides dates and times.

Get today's date

import datetime

x = datetime.datetime.now()
print(x)

Create your own date

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

The constructor takes year, month, and day, plus optional hour, minute, second, and microsecond.

The strftime method

strftime() formats a date into a string using directives.

x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B"))  # June

Common directives

DirectiveDescriptionExample
%aWeekday shortWed
%AWeekday fullWednesday
%bMonth shortJun
%BMonth fullJune
%yYear short18
%YYear full2018
%HHour 00-2317
%IHour 01-1205
%MMinute41
%SSecond08
%pAM/PMPM
%dDay of month01
%jDay of year152

Example

print(x.strftime("%A, %B %d, %Y"))
# Friday, June 01, 2018

TL;DR

  • datetime.datetime.now() gets the current date/time.
  • datetime.datetime(y, m, d) builds a specific date.
  • strftime("%Y") formats parts of a date.
  • Directives like %B and %Y pull out pieces.