tutorial, Python Programming  tutorial,Python DateTime module

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

     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 object

    Creating 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
      		#call date class constructor 
      		d =,month,day)
      		#print date object, print function converts date object into string before printing.
      		#i.e it is calling __str__ method
      		#Print  type of d object
      		<class ''>


date class fields to access Year, month and Day

      		d.year     #2020
      		d.month    #1     #1
Get 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 =;
      		#using instance method
      		now =,1,1)
      		Note: now  date object represents 2020-1-1 date 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 =,1,1)
      		d.weekday()  #2
      		d.isoweekday() #3
      		note: Year 2020 Jan 1st comes on WednesDay
Update 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-30
	d =, 1, 1)
>>> d=d.replace(year=2000)
>>> d, 1, 1)
>>> d=d.replace(year=2000,month=12)
>>> d, 12, 1)
>>> d=d.replace(year=2000,month=12,day=30)
>>> d, 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 =,1,1)
	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 MethodsDescription

Time class


      	 |  time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
Time class and its MethodsDescription

DateTime class

     Datetime class has both Date and Time information in a single class.

	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)


Find Last Day of the Month

     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 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):
      dt = datetime.datetime(year,month,day)
        return day
   except Exception as e:
>>> last_day(2000,2)
DateTime class and its MethodsDescription

Commonly used format codes:

    %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.