Working With Python datetime

Shriya Gupta
Analytics Vidhya
Published in
5 min readSep 16, 2019
Photo by Agê Barros on Unsplash

Python datetime is a module to work with dates in python which has basically 4 main objects for date and time operations: date, time, datetime and timedelta. Let’s learn about this step by step where we can do all sorts of operations using these 4 objects and solve problems gradually from easy to hard.

Introduction

Whenever we need to work with dates, date time module provides the necessary tools. Since, it is python’s standard library part so we don’t need to install it separately.

You can see below how it is imported:

The most important and commonly used object is the datetime class inside the datetime module.

Please don’t get confused with the name as the module name and class name is same.

Well, besides the datetime.datetime class, we also have other 3 classes:

1. date class

2. time class

3. timedelta class

1 — datetime.datetime.now()

Now, very basic question anyone can ask is how do we get current date and time in python? Let’s see!

datetime.datetime.now() can give you that. Quite easy right?

We can see here, the format follows YYYY,MM,DD,HH,MM,SS,MS and gives current date time in local date and time in local timezone.

2 — datetime.date.today( )

We can also get just the dates alone using datetime.date.today( ).

Since, today( ) is a method of the datetime.date class and it doesnot contain time information.

Good, but don’t you think above notation is hard to read. If you print, it out , it will show you in a nice YYYY-MM-DD format.

3 — datetime.datetime()

We saw above how to create datetime object for current time but let us see how to create it for any date and time.

We can pass it in the same order to datetime.datetime().

4 — dateutil.parser

Now, let’s learn about parsing. Parsing is nothing but converting datetime string to a datetime format because while working with spreadsheets columns or datasets, it can come in any format.

We can import parse from dateutil.parser.

Any datestring can be converted to a datetime object using dateutil.

Similarly, we can parse a datestring to datetime.

5 — strftime

Now, formatting datetime object into any date format. We can convert any datetime object to nearly any representation of date format using strftime() method.

6 — datetime Functions

Let’s learn some useful datetime functions.

6.1 — datetime.time()

We can use the datetime.time() to represent the time component alone.

6.2 — datetime.timedelta

Let us use timedelta to get the difference between two dates or times. Syntax: datetime.timedelta

I have a timedelta object that represents a duration of 30 days. Let’s compute the date that will be 20 days from now.

We can also subtract two datetime objects, we will get a timedelta object that represent the duration.

Similarly, we can subtract two time deltas to get another timedelta object.

7 — pytz (Timezones)

Let’s complicate it a little more now.

Working with time zones.For time zones, python recommends pytz module which is not a standard built-in library. You need to install it separately (enter `pip install pytz` in terminal or command prompt) So how to set time zone to a particular datetime? Simply pass the respective pytz timezone object to tzinfo parameter when you create the datetime. Then, that datetime will become timezone aware. Let’s create a datetime object that belongs to UTC timezone.

7.1 — pytz.all_timezones

UTC was a direct attribute of the pytz module. So, how to set to a different timezone? Lookup pytz.all_timezones for your timezone of choice. Then use the pytz.timezone() to create the respective timezone object that will be passed to the tzinfo argument.

Implementation

Now let’s see example on a flight dataset. You can download dataset from here

Step 1: Import library

Step 2: Lets read the data from excel

Step 3: Check how dataset looks like

Step 4: Convert Date_of_Journey to datatime from which we will extract feature

Step 5: Extract dayofweek from datetime

Step 6: Extract day from datetime

Step 7: Extract year from datetime

Step 8: Extract month from datetime

Let’s look how our dataset looks like after extracting time feature

Congratulations! You have successfully implemented python datetime on a dataset.

--

--