Python - Date Time

To work with dates in Python import a module 'datetime'

The date contains year, month, day, hour, minute, second, and microsecond.

Example 1: Display current date time

import datetime

x = datetime.datetime.now()
print(x)
2022-07-02 11:42:54.242601

Example 2: Same as example 1.

from datetime import datetime

x = datetime.now()
print(x)
2022-07-02 11:42:54.242601

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(2022, 5, 17)
print(x)
2022-05-17

The datetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of 0, (None for timezone).

Date Format

The datetime object has a method called strftime(), for formatting date objects into readable strings.

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%Y"))
2022
2022
Format Description Output
%a Weekday, short version Wed
%A Weekday, full version Wednesday
%w Weekday as a number 0-6, 0 is Sunday 3
%d Day of month 01-31 31
%b Month name, short version Dec
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version 22
%Y Year, full version 2022
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%f Microsecond 000000-999999 548513
%j Day number of year 001-366 365
%W Week number of year, Monday as the first day of week, 00-53 52
%x Local version of date 16/30/22
%X Local version of time 17:41:00