Working With Dates in Python
Last Updated :
17 Oct, 2021
In this article, we will discuss how to work with dates using python.
Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed. By using this module, You will get the time and date from the timezone that your local computer is present. This module just gets the date and time from the host computer ( Which in this case, it is your computer from which the program is executed ).
Date Class
Before diving into in-depth functions. Let's start with a simple program that returns today's date using the date object in the datetime module.
Syntax:
date.today()
Example: Get current date
Python3
# importing the module
from datetime import date
# storing today's date in a variable
today = date.today()
# Printing the variable
print(f"Today's date: {today}")
Output:
Today's date: 2021-09-28
today() method will give you the present date of your timezone. If you need just the year or month or day then you can use this method with the respective keywords.
Example: Getting date attribute wise
Python3
from datetime import date
today = date.today()
# to print the present year
print(f"Present Year:{today.year}")
# to print the present month
print(f"Present Month:{today.month}")
# to print the present date
print(f"Present Date:{today.day}")
Output:
Present Year:2021
Present Month:9
Present Date:28
Example: Program to count the number of days from the present date to a specific day
Python3
# Importing date from Datetime module
from datetime import date
# Storing today's date into a variable
today = date.today()
# Storing the specific date
graduation_day = date(2023, 8, 11)
# finding the difference of today's date from
# specified date
days_left = abs(graduation_day - today)
# Displaying the no.of.days left without time
print(f"Number of days left till graduation: {days_left}")
Output:
Number of days left till graduation: 682 days, 0:00:00
Datetime class
This method is similar to the date method but this is an upgraded version of the date object which will get you both the date and time from your local system. Let's write the same program, which we wrote for the date object but this time to calculate the remaining days with time.
Example: Program to count remaining days
Python3
from datetime import datetime
# By using now(), We will get both current
# date and time Storing current time and
# date into a variable
today = datetime.now()
# Storing the date and time you want to calculate
# In this you have to give the time as the input
graduation_day = datetime(2023, 8, 11, 0, 0, 0)
# finding the difference from
days_left = abs(graduation_day - today)
# Displaying the no.of.days left with time
print(f"Time left till the graduation: {days_left}")
Output:
Time left till the graduation: 681 days, 22:12:03.851113
Timedelta class
This object allows us to add or subtract time or date to a specific date and time.
Syntax :
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example: Adding and subtracting time
Python3
from datetime import datetime, timedelta
# adding 9 hours
hour_delta = timedelta(hours=9)
# Storing the new date
timeAdded = datetime.now() + hour_delta
# Displaying current date and time with
# adding 9 hours
print(f"The date after adding 9 hours: {timeAdded}")
# adding 1 day
day_delta = timedelta(days=1)
# storing the new date
dateAdded = datetime.now() + day_delta
# Displaying current date and time with
# adding 1 day
print(f"The date after adding 1 day: {dateAdded}")
Output:
The date after adding 9 hours: 2021-09-28 10:49:39.577570
The date after adding 1 day: 2021-09-29 01:49:39.577570
Parsing and formatting
If we want to convert the dates into readable strings, strftime() method is used.
Syntax:
time.strftime(format, t)
Parameters:
- format – This is of string type. i.e. the directives can be embedded in the format string.
- t – the time to be formatted.
Example: Converting date to string
Python3
import datetime
today = datetime.datetime(2021, 9, 10, 12, 30, 30)
print(today.strftime("%H:%M:%S %B %d %Y"))
Output:
12:30:30 September 10 2021
Parsing is used to convert a string into datetime format. strptime() is used to perform this. The parameters are date_string and format respectively.
Syntax :
strptime(date_string, format)
Example: Convert datetime to string
Python3
from datetime import datetime
print(datetime.strptime('26/5/2020', '%d/%m/%Y'))
Output:
2020-05-26 00:00:00
Similar Reads
Python | Calendar Module Python defines an inbuilt module calendar that handles operations related to the calendar. In this article, we will see the Python Program to Display Calendar. Calendar Module in PythonThe calendar module allows us to output calendars like the program and provides additional useful functions related
5 min read
Introduction to Python Calendar
Calendar in PythonPython has a built-in Python Calendar module to work with date-related tasks. Using the module, we can display a particular month as well as the whole calendar of a year. In this article, we will see how to print a calendar month and year using Python. Calendar in Python ExampleInput: yy = 2023 mm =
2 min read
Calendar Functions in Python | Set 2(monthrange(), prcal(), weekday()...)Some of calendar functions are discussed in the Set 1 1. monthrange(year, month) :- This function returns two integers, first, the starting day number of week(0 as monday) , second, the number of days in the month. 2. prcal(year, w, l, c) :- This function also prints the calendar of specific year bu
5 min read
Working with Dates in Python Calendar
How to Get Current Date and Time using PythonIn this article, we will cover different methods for getting data and time using the DateTime module and time module in Python.Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleIn
6 min read
Working With Dates in PythonIn this article, we will discuss how to work with dates using python. Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed. By
4 min read
Python program to print current year, month and dayIn this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date clas
1 min read
Formatting Dates in PythonIn different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can
5 min read
Calendar.Calendar Functions
Python calendar module : iterweekdays() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. iterweekdays() method return
1 min read
Python calendar module | itermonthdates() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdates() method retu
2 min read
Python calendar module : itermonthdays() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdays() method retu
1 min read
Python calendar module | itermonthdays2() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdays2() method is u
2 min read
Python calendar module : monthdatescalendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. monthdatescalendar() method
2 min read
Python calendar module : monthdays2calendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. monthdays2calendar() method
2 min read
Python calendar module | monthdayscalendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. monthdayscalendar() method i
2 min read
Python calendar module : yeardatescalendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. yeardatescalendar() method i
3 min read
Python calendar module : yeardays2calendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. yeardays2calendar() method i
3 min read
Python calendar module : yeardayscalendar() methodCalendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. yeardayscalendar() method i
2 min read
Calendar.TextCalendar Functions
Calendar.HTMLCalendar Functions
Simple TextCalendar Functions