×

Html & Html5

The World's best Software Development Study Portal

Python Dates


We are having datetime module to work in the datetime objects in Python. We just need to import datetime module .
Let's understand this by the following program :-


import datetime

x = datetime.datetime.now()

print(x)





Output of this Program


date.png

It will give you exactly the current date and time.



Creating date objects

If we want to create a date than we have to used the datetime class (constructor) of datetime module. And it basically requires three parameters like - year, month, day.
Let’s create a date object and understand it further :-:-

import datetime

x = datetime.datetime(2019, 6, 19)

print(x)





Output of this Program


date.png

We can see this datetime() class is not only taking the date-time format but also the time and time zone format.



The strftime () method

We can also format our date time into the readable string , and this method is only known as strftime() method.

import datetime

x = datetime.datetime(2018, 6, 1)

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





Output of this Program


date.png

So through these parameters we can check which date , day ,year and etc.



There are some more legal format codes which are described as follows :-

Directive 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 UTC offset +0100
%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
%% A % character %


python training insitute| Best IT Training classes in Gurgaon | python training