Time Functions in Python | Set 2 (Date manipulation)



Date manipulations can also be performed using Python using the “datetime” module and using the “date” class in it.

Date operations:

1. MINYEAR : — displays the minimum year that can be represented using a date class.

2. MAXYEAR : — displays the maximum year that can be represented using the date class.

# Python code to demonstrate how it works
# MINYEAR and MAXYEAR

 
# import inline datetime module

import datetime

from datetime import date

 
# using MINYEAR to print the minimum representable year

print ( "Minimum representable year is:" , end = "")

print (datetime.MINYEAR)

 
# using MAXYEAR to print maximum representable year

print ( "Maximum able year is: " , end = " ")

print (datetime.MAXYEAR)

Exit:

 Minimum representable year is: 1 Maximum representable year is: 9999 

3. date (yyyy-mm-dd) : — this function returns a string with the passed arguments in year, month and date order.

4. today () : — returns the date of the current day in yyyy-mm-dd format.

# Python code to demonstrate how it works
# date () and today ()

 
# importing the datetime built-in

import datetime

from datetime import date

 
# using date () to represent the date

print ( "The represented date is:" , end = "")

print (datetime.date ( 1997 , 4 , 1 ))

  
# using today () to print the current date

print ( "Present date is: " , end = " ")

print (date.today ())

Output:

 The represented date is: 1997-04-01 Present date is: 2016-08-02  

5. fromtimestamp (sec) : — Returns a date calculated in seconds since the time specified in the arguments.

6. min () : — returns the minimum date that can be represented by the date class.

7. max () : — returns the maximum date that can be represented by the date class.

# Python code to demonstrate how it works
# fromtimestamp (), min () and max ()

 
# importing the datetime plug-in

import datetime

from datetime import date

  
# using fromtimestamp () to calculate the date

print ( "The calculated date from seconds is : " , end = " ")

print (date.fromtimestamp ( 3452435 ))

 
# using min () to print the minimum representable date

print ( "Minimum representable date is:" , end = "")

print (date. min )

  
# using max () to print the minimum representable date

print ( "Maximum representable date is:" , end = " ")

print (date. max )

Output:

 The calculated date from seconds is: 1970- 02-09 Minimum representable date is: 0001-01-01 Maximum representable date is: 9999-12-31 

This article courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.