Python DateTime

Python provides three modules: datetime , time and calendar that help us to deal with dates, times, durations and calendars. The recent module is the 'datetime' module that deals with dates along with times. The 'datetime' module contains four important classes by the names 'datetime', 'date', 'time' and 'timedelta'.

  1. The datetime class handles a combination of date and time.It contains attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.
  2. The date class handles dates of Gregorian calendar, without taking time zone into consideration.It has the attributes: year, month, and day.
  3. The time class handles time assuming that every day has exactly 24 X 60 X 60 seconds.Its attributes: hour, minute, second, microsecond, and tzinfo.
  4. The timedelta class is useful to handle the durations.The duration may be the difference between two date, time, or datetime instances.

Current DateTime

Now The current date and time as shown in our computer system can be known using the following:

  1. ctime() method of 'time' module
  2. now() method of 'datetime' class of 'datetime' module
  3. today() method of 'datetime' class of 'datetime' module

When ctime() is used without passing any epoch time, it returns the current date and time in string format.

Current DateTime example:
CopiedCopy Code

#finding current date and time using ctime() 
import time 
t = time.ctime() 
print(t)

To know the current date and time, we can also take the help of now() method of 'datetime' class that belongs to 'datetime' module. This method returns an object that contains date and time information in any timezone. The time zone information should be provided to this method. If the time zone is not provided, then it takes the local time zone. For example, when we use this method in India, it gives the date and time according to IST (India Standard Time) that is 5.30 hours ahead of Greenwich Mean Time. This is called local time zone of India.

DateTime Format

CopiedCopy Code

#finding current date and time 
from datetime import * 
now = datetime.now() 
print(now) 
print('Date now: {}/{}/{}'.format(now.day, now.month, now.year)) 
print('Time now: {}:{}:{}'.format(now.hour, now.minute, now.second))
DateTime Format Example
CopiedCopy Code

#finding today's date and time 
from datetime import * 
#today() of datetime class gives date and time 
tdm = datetime.today() 
print("Today's date and time= ",tdm) 
#today() of date class gives the date only 
td = date.today() 
print("Today's date=", td)