To work with dates in python, we need to import a module to our code. This python date module is python datetime module.
With the below code, we can print the current time with a python code.
The output of this code will be the time of now which contains year, month, day, hour, minute, second, and microsecond values of the current time.
There are different methods used with datetime module of python. Below, you will find some of the examples on these methods.
In Python to create a date object, we use datetime module. Firstly, we import this module and then, we use three key parameters of this method to create this date object. Below, there is an example for this.
The output of this code will be:
In Python there is an important method used with time named python strftime method. With this method, we can format date objects into readable format. This method takes one parameter and the related parameters are given below with their meanings.
Let’s think about the time of now. Here, below letters will give us the below outputs about the time.
%a Day name (short) Tue
%A Day name Tuesday
%w Day Number (Sunday=0) 2
%d Day of month (01-31) 16
%b Month name (short) Nov
%B Month name November
%m Month number 11
%y Year (short) 21
%Y Year 2021
%H Hour 23
%I Hour (00-12) 11
%p AM/PM PM
%M Minute 16
%S Second 05
%f Microsecond 254765
%Z Timezone CST
%j Day number 320
%W Week number 46
%C Century 20
%x Local version of date 11/16/21
%X Local version of time 23:16:00
%c Local date and time Mon Dec 31 23:16:00 2021
Let’s do an example with strftime method of python.
The output of this python strftime method code will be:
In this python time lesson, we have learned how to work with times and date in python programming. You can use these methods and python datetime module in your various projects.