Python Dates

Python Datetime Module

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.


Getting the Current Date

Datetime Example

import datetime

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

The date contains year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object.


Creating Date Objects

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.

Creating Specific Dates

import datetime

x = datetime.datetime(2020, 5, 17) print(x)


The strftime() Method

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.

Formatting Dates

import datetime
x = datetime.datetime.now()

print("Year:", x.strftime("%Y")) print("Weekday:", x.strftime("%A")) print("Month:", x.strftime("%B"))