In this tutorial, we will cover python datetime module and how it is used to handle date, time and datetime formatted columns (variables). It includes various practical examples which would help you to gain confidence in dealing dates and times with python functions. In general, Date types columns are not easy to manipulate as it comes with a lot of challenges like dealing with leap years, different number of days in a month, different date and time formats or if date values are stored in string (character) format etc.
READ MORE »
Table of Contents
Introduction : datetime module
It is a python module which provides several functions for dealing with dates and time. It has four classes as follows which are explained in the latter part of this article how these classes work.- datetime
- date
- time
- timedelta
People who have no experience of working with real-world datasets might have not encountered date columns. They might be under impression that working with dates is rarely used and not so important. To enlighten them, I have listed down real-world examples wherein using datetime module can be beneficial.
- Selecting all the saving account holders who were active on 30th June, 2018 and checking their status whether they are still active
- Identifying insureds who filed more than 20 claims in the last 3 months
- Identifying customers who made multiple transactions in the last 6 months
- Extracting dates from timestamp values
Import datetime module
You can import or load datetime module by using the command below - import datetimeYou don't need to install this module as it comes bundled with the installation of python software.
Dates
Here we are usingdatetime.date
class which is used to represent calendar date values. today()
method is used to fetch current date. datetime.date.today()In order to display it like a proper calendar date, we can wrap it within
Output
datetime.date(2019, 7, 19)
print( )
command.
print(datetime.date.today())
Output
2019-07-19