1 min read

Python Dates

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.

Importing the Module

import datetime

Get Current Date

To display the current date, we can use the datetime.now() method.

import datetime

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

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.

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.

import datetime

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

print(x.strftime("%B")) # Output: June

Common Format Codes

  • %a: Weekday, short version (e.g., Wed)
  • %A: Weekday, full version (e.g., Wednesday)
  • %b: Month name, short version (e.g., Dec)
  • %B: Month name, full version (e.g., December)
  • %Y: Year, full version (e.g., 2018)

programming/python/python