Python Dates import datetime x = datetime.datetime.now() print(x)
In Python, a date is not a data type of its own i.e. date is not a specific datat type in python, but we can import a module named datetime if we want to work with dates as date objects.
To import the datetime module and display the current date, we write the following code:
Date Output import datetime x = datetime.datetime.now() print(x.year) print(x.strftime("%A"))
When we execute the code from the above example then the output will be:
2019-07-27 18:05:52.105722
The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many functions 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:
Creating Date Objects import datetime x = datetime.datetime(2020, 5, 17) print(x)
To create a date, we can use the datetime() class constructor of the datetime module.
The datetime() class needs three parameters to create a date: year, month, day.
To create a date object, we write the following code:
The datetime() class also takes parameters for time and timezone (like 'hour', 'minute', 'second', 'microsecond', 'tzone'), but these are optional, and has a default value of 0, ("None" in case of timezone). import datetime x = datetime.datetime(2018, 6, 1) print(x.strftime("%B"))
The strftime() Method
The datetime object has a method that will format the date objects into readable strings.
The method which performs this task is called strftime(), and takes one parameter, format, to specify the format of the returned string:
Example: Display the name of the month: