Python Date

Python Date

In Python, dates are not their own data type, but we can import a module named datetime module, treating dates as date objects.

Example

Import datetime Module and display the current date:

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

Running instance

Date output

If we run the above code, the result will be:

2019-08-14 12:52:55.817273

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

datetime The module has many methods that can return information about the date object.

Here are some examples, which you will learn in detail later in this chapter:

Example

Return the name of the weekday and the year:

import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))

Running instance

Create date object

To create a date, we can use the datetime module's datetime() Class (constructor).

datetime() The class requires three parameters to create a date: year, month, and day.

Example

Create a date object:

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

Running instance

datetime() The class also accepts time and timezone (hour, minute, second, microsecond, tzone) parameters, but they are optional, with default values of 0,(The timezone is set to None)。

strftime() method

datetime The object has a method to format the date object into a readable string.

This method is called strftime(), and use a format Parameters to specify the format of the returned string:

Example

Display the name of the month:

import datetime
x = datetime.datetime(2019, 10, 1)
print(x.strftime("%B"))

Running instance

Reference for all valid format codes:

Command Description Example TIY
%a Weekday, short version Wed Try It Yourself
%A Weekday, full version Wednesday Try It Yourself
%w Weekday, number 0-6, 0 is Sunday 3 Try It Yourself
%d Day, number 01-31 31 Try It Yourself
%b Month name, short version Dec Try It Yourself
%B Month name, full version December Try It Yourself
%m Month, number 01-12 12 Try It Yourself
%y Year, short version, without century 18 Try It Yourself
%Y Year, full version 2018 Try It Yourself
%H Hour, 00-23 17 Try It Yourself
%I Hour, 00-12 05 Try It Yourself
%p AM/PM PM Try It Yourself
%M Minute, 00-59 41 Try It Yourself
%S Second, 00-59 08 Try It Yourself
%f Microseconds, 000000-999999 548513 Try It Yourself
%z UTC offset +0100 Try It Yourself
%Z Time zone CST Try It Yourself
%j Day number, 001-366 365 Try It Yourself
%U Week number, the first day of the week is Sunday, 00-53 52 Try It Yourself
%W Week number, the first day of the week is Monday, 00-53 52 Try It Yourself
%c Local version of date and time Mon Dec 31 17:41:00 2018 Try It Yourself
%x Local version of date 12/31/18 Try It Yourself
%X Local version of time 17:41:00 Try It Yourself
%% A % character % Try It Yourself