18.dates

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.

To get today's Date

import datetime

x = datetime.date.today()
print(x)

Output:
2020-07-02

To get the present time

import datetime

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

Output:
2020-07-02 15:39:00.085950

datetime.now() result contains year, month, day, hour, minute, second, and microsecond.

Creating Date Object

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 Date Object

import datetime

x = datetime.datetime(2020, 7, 7)

print(x)

Output:
2020-07-07 00:00:00

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).

Manipulating the date

We can change any instance of date like year, month or day.

Example

d1 = datetime.date(2020,7,3)
print(d1)

Output:
2020-07-03

d2 = d1.replace(year = 1990)
print(d2)

Output:
1990-07-03

print(d1-d2)

Output:
10958 days, 0:00:00

The strftime() Method

The strftime() Method is used to format the date objects into readable strings. This function converts time input into a string output.

This methods takes one parameter, format, to specify the format of the desired returned string.

To display the name of the month

import datetime

x = datetime.datetime(2020, 7, 2)

print(x.strftime("%B"))

Output:
July

A reference of all the legal format codes

Derivate Description Example
%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, without century 18
%Y Year, full version 2018
%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
%Z Timezone CST
%j Day number of year 001-366 365
%U Week number of year, Sunday as the first day of week, 00-53 52
%W Week number of year, Monday as the first day of week, 00-53 52
%c Local version of date and time Mon Dec 31 17:41:00 2018
%x Local version of date 12/31/18
%X Local version of time 17:41:00