Introductory note on Data Science using Python programming language. (Article.2: Python Dates and times and, Brief note on Python Objects.)

Ayush Singh
Analytics Vidhya
Published in
5 min readMay 16, 2020

Welcome to another article on “Introductory note on Data Science using Python programming language”, and this article as the title says will let you know how to access Dates and Times in Python, a brief application and then on the other part we will be having Advanced python objects, and use the map() function. If you are new to Data Science I would recommend you, to read the first article on this series, as this article would probably fail to let you have a clearer vision of python. A lot of analysis we do might relate to dates and times. For instance, let's consider finding the average number of sales over a given period, selecting a list of products to data-mine if they were purchased in a given period, validating assignment uploads over a period of time, or trying to find the period with the most activity in online discussion forum systems, so you see we have tons of applications. Starting with times and dates, I would like to mention that you won't see a detailed discussion regarding times and dates, but I hope you definitely build a strong base for this topic, and this article will have more words than codes.

Dates And Times

Let's get started, first, you should be aware that date and times can be stored in many different ways. One of the most common legacy methods for storing the date and time in online transaction systems is based on the offset from the epoch, which is January 1, 1970. There’s a lot of historical cruft around this, but it’s not uncommon to see system storing the date of a transaction in seconds or milliseconds since this date. So if you see large numbers where you expect to see date and time, you’ll need to convert them to make much sense out of the data and make it easier for the users to execute their work. In Python, you can get the current time since the epoch using the “time” module.

import datetime as dt
import time as tm
print(tm.time())
#prints the time in seconds since epoch(January 1,1970)

So this was the large numbers I was talking about, the numbers printed on your console, hence let's move forward and come up with more sensible outputs. You can create a timestamp using the “fromtimestamp” function on the date-time object. When we print this value out, we see that the year, month, day, and so forth can also be printed out, using the “dtnow.year”, “dtnow.month”, “dtnow.day”, and so on.

#Convert the timestamp to datetime.
dtnow = dt.datetime.fromtimestamp(tm.time())
print(dtnow)#prints the current date and time
print(dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second)
#extract year, month, day, etc.from a datetime

Date time objects allow for simple math using time deltas. Now, what exactly are time deltas? A time delta is a duration expressing the difference between two dates. For instance, here, in the code given below, we can create a time delta of 10 days.

delta = dt.timedelta(days = 10) # create a timedelta of 10 days

Now that a time delta is created we will do some basic operations and comparisons with the date time object, between the current date and the date after the given time delta duration.

today = dt.date.today()
print(today)
'''prints the current date (dtnow prints the date as well as time, hence this is the basic differnce).'''
print('After 10 days: '+str(today + delta)) # the date 10 days
print(today > today-delta) # compare dates

So this was just a little glimpse at dates and times in Python, and for basics, this would be enough.

Moving on, we will now talk about Python Objects.

A brief note on Objects

Up to this point, we haven’t seen much of object-oriented Python, and as of now, you might have noticed. functions play a big role in the Python world, and Python does have classes that can have attached methods, and be instantiated as objects. Before moving on if you are thinking this article is about the nitty-gritty details of objects in Python or object-oriented programming, then you're thinking off the mark. In the due course of time, the more you will work with Python you’ll use objects a lot, and less likely to be creating new classes when you use the interactive environment because it’s a bit verbose. But I think it’s important to go over a few details of objects in Python, just so that you aren’t surprised when you see them.

You define a class in Python using the “class” keyword, followed by a colon. Anything intended below this will be considered as the body of the class. I recommend you to follow the camel casing convection while naming a class. Below you will find some lines of codes because I want you to see first how a class is defined, and after this, I will provide more details of the code.

class Person:
department = 'School of Information' #a class variable
def set_name(self, new_name): #a method
self.name = new_name
def set_location(self, new_location):
self.location = new_location

To define a method, you just write it as you would have a function. The one change is that to have access to the instance which a method is being invoked upon, you must include self, in the method signature. Similarly, if you want to refer to instance variables set on the object, you prepend them with the word self, with a full stop.
In this definition of a person, for instance, we have written two methods. Set name and set location. And both change instances bound variables, called name and location respectively. When we run this cell, we see no output. The class exists, but we haven’t created any objects yet. We can instantiate this class by calling the class name with empty parenthesis behind it. Then we can call functions and print out attributes of the class using the dot notation, common in most languages.

person = Person()
person.set_name('Christopher Brooks')
person.set_location('Ann Arbor, MI, USA')
print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))
'''
OUTPUT:
Christopher Brooks live in Ann Arbor, MI, USA and works in the department School of Information
'''

There are two important implications of object-oriented programming in Python, that you should take away from this very brief example. First, objects in Python do not have private or protected members. If you instantiate an object, you have full access to any of the methods or attributes of that object, in simple words “IT’S PUBLIC!”. Second, there’s no need for an explicit constructor when creating objects in Python. You can add a constructor if you want to by declaring the __init__ method. Now I’m not going to dive any more into Python objects, because there’s lots of subtlety, and, to be honest, most of the object-oriented features of Python aren’t really all that salient for introduction to data science.

That will be enough for this article, but definitely more articles will be published focusing on Data Science using Python.
Stay tuned if you’re interested in Data Science and liked this article, and I would love to interact with you if you have any queries.
Thank you so much for reading this article! I hope it helped you in some way or the other.

(GitHub: https://github.com/ayush-670)

--

--

Ayush Singh
Analytics Vidhya

A web designer, flutter developer, and the sugar to your coffee.