Formatting dates in Python
In, this tutorial we will learn about formatting dates in Python. We use the datetime module to do so. datetime is an inbuilt module in Python that allows us to easily work with dates and times.
This is especially useful as the date representation varies from place to place. For example, dd-mm-yyyy is used in India whereas mm-dd-yyyy is used in the U.S.
Formatting dates in Python using the datetime module
The datetime module contains various attributes to help us work with date and time objects.
The ‘date’ class is a class present in the datetime module. We make use of this to represent years, months and dates. One (wrong) assumption used by date is that the Gregorian calendar has always, is and always will be used. Nevertheless, it works fine for dates in recent memory.
In the next section, we look at a few examples of formatting dates using the date class. Also, please remember to first import the datetime module.
Applications of the date class
We can use the today() function to get today’s date in the format yyyy-mm-dd as shown below.
# we create a date object 't' having today's date t = datetime.date.today() print(t)
We create a date object by calling the constructor. We pass the year, month and date as parameters. Please ensure that you enter valid inputs. For example, we must not enter dates with leading 0s (8 and not 08). Another example is that we must only enter years from 1 to 9999. The individual attributes of the object with the ‘.’ operator.
# create a date object with valid year, month and date t = datetime.date(2013, 8, 9) print(t) # year, month and date can be accessed individually using '.' print(t.day, t.month, t.year)
2013-08-09 9 8 2013
Another useful function in the date class is strftime(). This allows us to conveniently represent dates with the help of strings. We call it as a method of an already created date object. It returns a string according to the specified format codes (for example, “%d”, “%Y”, etc). The use of a few format codes is shown below.
# create a date object with valid year, month and date t = datetime.date(2013, 8, 9) print(t) # to print dd just_the_date = t.strftime("%d") print(just_the_date) # to print mm just_the_month = t.strftime("%m") print(just_the_month) # to print yy (2013 is represented as 13) just_the_yy = t.strftime("%y") print(just_the_yy) # to print yyyy just_the_year = t.strftime("%Y") print(just_the_year) # to print the day just_the_day = t.strftime("%A") print(just_the_day) # we can also print a combination of these as shown below print(t.strftime("%d/%m/%Y was a %A."))
2013-08-09 09 08 13 2013 Friday 09/08/2013 was a Friday.
In this tutorial, we learnt how to format dates using Python. We are easily able to this with the help of the datetime module and the date. Finally, we also learned to convert dates to strings.