Python Dates Overview

Python me kai tarah ke built-in Modules hote hain jinhe requirement ke hisab se time to time import kiya jata hai. Thik issi tarah python me “Date” bhi ek module hai, jiska use kai cases me kiya jata hai.

Date Module ko import karne ka tarika :
import datetime            

Date module ke through current date print karna

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

Upar diye code execute hone ke baad kuch aisa output dega :
2020-11-05 10:53:23.628907           
“year-month-date hour:minute:second.microsecond”

Upar diye gaye code me “datetime.datetime.now()” use kiya gaya hai, jaha pahla “datetime” ek module hai aur dusra “datetime” ek class constructor hai jo finally “now()” function ko call kar raha hai.

hum upar diye code code ko aisa bhi likh sakte hain, jaha dt ek alias naam hai jo datetime module ko hi represent kar raha hai.

import datetime as dt          
a = dt.datetime.now()
print(a)

Datetime Class ke Parameters

Dekha jaye to Datetime class ke important 3 parameters hote hain jinhe define karna mandatory hota hai – Year, Month & Date. Iske alawa timezone ka bhi parameter hota hai jo optional hota hai.

import datetime as dt            
a = dt.datetime(2020,5,11)
print(a)

strftime() Method ka best use

strftime() Function Datetime module me use hone wala important function hai. jaha tak naam se hi samajh me aa raha hai ki strftime() function time ko string ke format me convert karke readable form me present karta hai.

Example se samajhte hain:

import datetime as dt            
a = dt.datetime(2020,5,11)
print(a.strftime(“%A”))

Output : “Monday”

upar diye gaye example me strftime() function ke sath “%A” ka use kiya gaya hai, jo date ke according particular day print karega. 

Formatting Parameters jo strftime() method ke sath use hote hain

%B  
%b  
%A 
%a 
%%
%X
%x 
%W
%w
%c 
%d  
%Y 
%y
%H 
%S 
%Z 
%I 
%f
%M 
%m

Full name of Month (Ex : January)
Short name of month (Ex : Jan)
Full name of Day (ex : Monday)
Short name of Day (ex : Mon)
print with % character 
Time according to timezone
Date according to timezone
Date ke according week number
Day ka number (like : Mon = ‘1’, Wed = 3)
Local version of Date & Time
Date of month
Full name of year
short format of year
Display Hour between 00-24
Second 00-60
Display Timezone
Display Hour between 00-12
Display microseconds 
Display Minutes (00-59)
Display month (0-12)