DateTime For Python
DateTime For Python
Example:
import datetime
x = datetime.datetime.now()
print(x)
The date contains year, month, day, hour, minute, second, and
microsecond.
1
x = datetime.datetime.now()
print(x.year)
print(x.strftime(“%A”))
Output:
2020
Tuesday or the day today
x = datetime.datetime(2020, 5, 17)
print(x)
Output:
2020-05-17 00:00:00
Example
Display the name of the month:
import datetime;
x = datetime.datetime(2018, 6, 1);
print(x.strftime("%B"));
Output:
June or the name of the current month
import datetime;
x = datetime.datetime(2018, 6, 1);
print(x.strftime("%a-%B"));
Output:
Wed-June
2
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 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
%j Day number of year 001-366 365
%c Local version of date and time Mon Dec 31 17:41:00
%x Local version of date 12/31/18
%X Local version of time 17:41:00
Formatting Time
You can format time in many different ways with the print
function. There are also several ways to get readable time
format in Python. A simple way to get time is with the
asctime() function. Here’s an example:
import time
time_now = time.asctime( time.localtime())
print("Current date and time is:", time_now)
Output:
Current date and time is: Tue Jul 21 09:39:29 2020
Calendar Module
import calendar
July_cal = calendar.month(2016, 7)
3
print (“Calendar for the month of:”)
print (July_cal)
calendar.firstweekday( )
The function returns the setting for the first weekday of the
week. The default starting day is Monday which is equivalent
to o.
print(calendar.firstweekday())
Output:
0
calendar.isleap(year)
print(calendar.isleap(2016))
print(calendar.isleap(2014))
Output:
True
False
calendar.leapdays(y1, y2)
This function returns the sum of leap days within a given range.
print(calendar.leapdays(2010, 2016))
Output:
4
1
calendar.monthrange(year, month)
This function returns two integers. The first integer denotes the
weekday code (o to 6) for the first day of the month in a given
year. The second indicates the number of days in the specified
month (1 to 31).
print(calendar.monthrange(2020, 7))
Output:
(2, 31)
print(calendar.weekday(2020,6,30))
Output:
1