Python Date and Time

Python gives the developer several tools for working with date and time . The standard libraries contains the modules such as:
  1. datetime
  2. time
  3. calendar
datetime: datetime is a module which is designed with object-oriented programming to work with date and time in Python . It defines several classes that represent date and time. time: time is a module that only includes functions, and constants related to date and time , there are several classes written in C/C ++ defined on this module. For example, the struct_time class. calendar: The calendar is a module that provides functions, and several classes related to Calendar, which support generating images of the calendar as text, html, These modules supply classes for manipulating dates and times in both simple and complex ways.

datetime Object

Datetime objects are probably one of the most used in any application. A datetime object is an instance of the datetime.datetime class that represents a single point in time. The datetime module includes functions and classes for doing date and time parsing, formatting, and arithmetic. So the datetime module can be imported like this:
import datetime

How to get current time in Python?

import datetime print(

Calendar date values are represented with the date class. Instances have attributes for year, month, and day.

import datetime today = print("Day : ", print("Month : ", today.month) print("Year : ", today.year) print("Hour : ", today.hour) print("Minute : ", today.minute) print("Second : ", today.second)

time object

Time values are represented with the time class. Times have attributes for hour, minute, second, and microsecond.

Getting current time

import time; ltime = time.localtime(time.time()) print ("Local current time :", ltime)

Format the current time in Python

You can format any time as per your requirement, but a simple method can do so by calling time.strftime(format[, t]) with the current time object as the argument t. If the t argument is not provided or None, then the time_struct object returned by time.localtime is used. example
import time; ltime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", ltime)

calendar object

Python has a built-in function, calendar to work with date related tasks. It defines the Calendar class , which encapsulates calculations for values such as the dates of the weeks in a given month or year. example
import calendar year = 2010 month = 10 print(calendar.month(year, month))
October 2010 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31