Classes you may like
Python datetime Module
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.
Example
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Date Output
When we execute the code from the example above the result will be:
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Here are a few examples, you will learn more about them later in this chapter:
Example
Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
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.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
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).
The strftime() Method
The datetime object has a method for formatting date objects into readable strings.
Python datetime module
In Python, date and time are not a data type of its own, but a module named datetime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. Datetime module supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times and time intervals. Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps.
The datetime classes are categorize into 6 main classes –
Date class
When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.
Constructor syntax:
class datetime.date(year, month, day)
The arguments must be in the following range –
Note – If the argument is not an integer it will raise a TypeError and if it is outside the range a ValueError will be raised.
# Python program to
# demonstrate date class
# import the date class
fromdatetime importdate
# initializing constructor
# and passing arguments in the
# format year, month, date
my_date =date(1996, 12, 11)
print("Date passed as argument is", my_date)
# Uncommenting my_date = date(1996, 12, 39)
# will raise an ValueError as it is
# outside range
# uncommenting my_date = date('1996', 12, 11)
# will raise a TypeError as a string is
# passed instead of integer
For more, checkout W3Schools and Geeks For Geeks.