Loading lessons...
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
| Directive | Description | Example |
|---|---|---|
%a | Weekday short | Wed |
%A | Weekday full | Wednesday |
%b | Month short | Jun |
%B | Month full | June |
%y | Year short | 18 |
%Y | Year full | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 01-12 | 05 |
%M | Minute | 41 |
%S | Second | 08 |
%p | AM/PM | PM |
%d | Day of month | 01 |
%j | Day of year | 152 |
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.