Python DateTime Module Example
Python DateTime related classes and functions exists in datetime module. Main classes in this module are date,time,and datetime
time object represents only time in (hours,minutes,seconds and nano seconds)
date object represents only date fields(year,month day)
datetime represents , both date and time fields
import datetime
Date class can be created by passing Year,month and Day of the month, all fields are mandatory. Year can start from 1 to 9999.
Creating a date objectCreating a date class requires year, month and day. Date class has constructor, which takes three parameters,Year,month and day.Once user passes valid values,or values within the range, date object will be created successfully.
import datetime #Initialize variables year=2020; month=1 day=1 #call date class constructor d = datetime.date(year,month,day) #print date object, print function converts date object into string before printing. #i.e it is calling __str__ method print(d) 2020-01-01 #Print type of d object print(type(d)) <class 'datetime.date'>
date class fields to access Year, month and Day
d.year #2020 d.month #1 d.day #1Get Today's date
Today's date can be object using Date class statc method today() and also each instance of the Date object has method called today(), so both ways user can get current date.
#Using date class static method now = datetime.date.today(); print(now) 2023-2-23 #using instance method now = datetime.date(2020,1,1) print(now.today()) 2023-2-23 Note: now date object represents 2020-1-1 date now.today() returns system's date.day and weekday,isoweekday methods
day represents day of the month, weekday represents a value,i.e Monday=0,Tuesuday=1,sunday=6, where as isoweekday reprents a value i.e Monday=1,Tuesday=2...Sunday=7
d = datetime.date(2020,1,1) d.weekday() #2 d.isoweekday() #3 note: Year 2020 Jan 1st comes on WednesDayUpdate Date Object using Replace method
Date object has 3 main fields, Year, Month and Day, these values can be updated using Replace method, Which accepts Keyword Arguments Year, Month,Day , using this, user can update individual field
Here date object represents 2020-1-1 , using replace method updating it to 2000-12-30d = datetime.date(2020, 1, 1) >>> d=d.replace(year=2000) >>> d datetime.date(2000, 1, 1) >>> d=d.replace(year=2000,month=12) >>> d datetime.date(2000, 12, 1) >>> d=d.replace(year=2000,month=12,day=30) >>> d datetime.date(2000, 12, 30)Formatting Date Object
Date object can be formatted into various forms using strftime method.
Format codes for date object%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name.
strftime methods takes format string as a input, The input should contain above format codes,to extract individual fields from date object and converted into a string
d = datetime.date(2020,1,1) d.strftime("%Y-%m-%d") '2020-01-01' d.strftime("%a %Y-%m-%d") 'Wed 2020-01-01' d.strftime("%A %Y-%m-%d") 'Wednesday 2020-01-01' d.strftime("%b %d %Y") 'Jan 01 2020' d.strftime("%B %d %Y") 'January 01 2020'
Date class and its Methods | Description |
Syntax:
| time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
Time class and its Methods | Description |
Datetime class has both Date and Time information in a single class.
Syntax:datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) all fields are integers except tzinfo, which represents timezone information square brackets indicates optional fields. so for creating a datetime object, user must provide year,month and day, optionally time information(hours,minutes,seconds)Create datetime object
import datetime.datetime dt = datetime.datetime(2000,1,1) dt = datetime.datetime(2000,1,1,0,0,1) dt=datetime.datetime(year=2000,month=1,day=1) dt=datetime.datetime(year=2000,month=1,day=1,hour=0,minute=0,second=1)
Finding last day of the month, for this example using datetime class, Year can be from range 1..9999, where as month should be 1..12 range, Day range changes based on the Year and Month. for Leap Year, Feb has 29 days,non-leap years Feb has 28 days, other months also has 30 days or 31 days. In order to find last day of the month passing day range from 31 to 28, for a given month has 30 days only, if you pass 31 days,datetime class creation fails, that means that month has 30 days or 29 days or 28 days.so ignoring 31 value, checking with 30... this process continues till it gets a valid last day .
import datetime.datetime def last_day(year,month): for day in range(31,27,-1): try: dt = datetime.datetime(year,month,day) return day except Exception as e: pass >>> last_day(2000,2) 29
DateTime class and its Methods | Description |
%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z DateTime zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and DateTime representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM.
ADS