Datetime Module

Python has the datetime module to help deal with timestamps in our code. Time values are represented with the time class.

Times have attributes for hour, minute, second, and microsecond. They can also include time zone information. The arguments to initialize a time instance are optional, but the default of 0 is unlikely to be what you want.


time

we can extract time information from the datetime module. We can create a timestamp by specifying datetime.time(hour,minute,second,microsecond)

A time instance only holds values of time, and not a date associated with the time.

	
#  Syntax : 
	
	import datetime
	
	t = datetime.time(10, 20, 1)
	
	#  Examples : 
	print(t)
	print('hour  :', t.hour)
	print('minute:', t.minute)
	print('second:', t.second)
	print('microsecond:', t.microsecond)
	print('tzinfo:', t.tzinfo)
		

The min and max class attributes reflect the valid range of times in a single day.

	
#  check the min and max values : 
	
	print('Earliest  :', datetime.time.min)
	print('Latest    :', datetime.time.max)
	print('Resolution:', datetime.time.resolution)
	
		

Dates

datetime (as you might suspect) also allows us to work with date timestamps. Calendar date values are represented with the date class. Instances have attributes for year, month, and day. It is easy to create a date representing today’s date using the today() class method.

	
#  Syntax : 
	
	today = datetime.date.today()
	
	#  Examples : 
	print(today)
	print('ctime:', today.ctime())
	print('tuple:', today.timetuple())
	print('ordinal:', today.toordinal())
	print('Year :', today.year)
	print('Month:', today.month)
	print('Day  :', today.day)
		
	
#  Syntax : 
	
	print('Earliest  :', datetime.date.min)
	print('Latest    :', datetime.date.max)
	print('Resolution:', datetime.date.resolution)
		

replace() methods

	
#  Syntax : 
	d1 = datetime.date(2015, 3, 11)
	print('d1:', d1)

	d2 = d1.replace(year=1990)
	print('d2:', d2)
		

Arithmetic :

We can perform arithmetic on date objects to check for time differences.

This gives us the difference in days between the two dates. You can use the timedelta method to specify various units of times (days, minutes, hours, etc.)

	
#  Syntax : 
	
	d1 = datetime.date(2015, 3, 11)
	
	d2 = datetime.date(1990, 3, 11)
	
	d1-d2
		datetime.timedelta(9131)