Date and Time

Date and Time


  Machine Learning in Python

Summary : Date and time calculation can get pretty cumbersome if we have to do it ourselves without help from external libraries. Python has standard libraries that let us deal with this.

Contents

There are 4 key objects in Python’s datetime module. Depending on the requirements, you can select the appropriate object.

key objects in datetime module of python

Date Object

Let’s first deal with just date ( not time ) . The date object just deals with the date – year, month and day of the month – and doesn’t include time.

date object – key attributes & initialization

There are a couple of ways to initialize a date object.

from datetime import date 
datetime.date(2019, 4, 2) 
today = date.today() 
import time
from datetime import date

today = date.fromtimestamp(time.time())

The key attributes ( day, month and year ) can be extracted using the read-only attributes – day, month & year

today.day
# and by default
# today.month
# today.year

Once a date object is created, you can replace specific attributes (day, month or year) using the replace function.

replace function of year

You can also extract which day of the week ( monday, tuesday etc ) of the week the current date is.

weekday () function in date object

You can format the date object into a string using the strftime () function. The specifics of formatting can be found here.

strftime () function in date object

from datetime import date

today = date(2019,12,01)

print ( today.strftime("%b '%y"))
Question – Execute the code above and select the correct output from the choices below.
Dec ‘2019
12 ‘2019
12 ’19
Dec ’19

from datetime import date

today = date(2019,1,18)

print ( today.strftime("%W"))
Question – Execute the code above and select the correct output from the choices below.
5
4
3
2

from datetime import date

today     = date(2019,1,7)
yesterday = date(2019,1,6)

print ( yesterday-today)
Question – Execute the code above and select the correct output from the choices below.
1 day
-1 day

Timedelta Object

The function today returns today’s date. What is tomorrow ?

from datetime import timedelta 
tomorrow = today + timedelta(days = 1 ) 
datetime.date(2019, 4, 2) 

You can also add weeks, days, hours, minutes, seconds or even microseconds. The module timedelta can be used to add a particular delta unit of time – it could be weeks or days or hours, even up to microseconds.

You can extract specific information like day or month or year from the date object

1 

What if you wanted to subtract one date from another ? Say, how many days between today and 1 week from now ? You can use the  operator, just like how you would subtract numbers.

today = date.today()
week  = today + timedelta(weeks = 1) 
week-today 
datetime.timedelta(days=7) 

You can create date objects for a particular date. For example, say my birthday is on June 15, 1985. We can put it is as

birthday = date(1985,6,15) 

Now that we know how to create date objects from scratch, let’s do a small calculation. How many days till my next birthday ?  

Allowed operator overloading methods for date object

from datetime import date

today     = date(2019,1,7)
yesterday = date(2019,1,6)

type(today - yesterday)
Question – Execute the code above and select the correct output from the choices below.
time
date
timedelta
datetime

from datetime import date

today     = date(2019,1,7)
yesterday = date(2019,1,6)

today < yesterday
Question – Execute the code above and select the correct output from the choices below.
True
False

from datetime import date, timedelta

today     = date(2019,1,7)

print ( (today - timedelta(days = 2)).day )
Question – Execute the code above and select the correct output from the choices below.
7
5

from datetime import date, timedelta

today     = date(2019,3,7)

print ( (today - timedelta(months = 2)).month)
Question – Execute the code above and select the correct output from the choices below.
1
error

from datetime import date

today     = date(2019,1,7)
yesterday = date(2019,1,6)

print ( (yesterday - today).days )
Question – Execute the code above and select the correct output from the choices below.
1
-1

How many days till my next birthday

We know each of the following

– today

– birthday

Now, we have to calculate days until my next birthday. This requires a bit of manipulation, especially with the year. Since the birthday is way in the past, we need to reset it to this year (or the next ) depending on if the birthday has already passed or is it still ahead

next_birthday = date(today.year,birthday.month,birthday.day) 

Has it already passed this year or is it still ahead ?

# birthday already passed this year. So, calculate until the next year 
if next_birthday < today :     
    next_birthday = date(today.year+1, birthday.month, birthday.day) 

Now, all we have to do is calculate the delta days.

number_days = next_birthday - today 
number_days 
datetime.timedelta(days=74) 

datetime.time Object

Similar to the date module, the datetime module has another object called the time object. It has the following key attributes

  • hour
  • minute
  • second
  • microsecond

Unlike the Unix time stamp, this object is not absolute. It is relative to 12:00 midnight of that particular day. Essentially, it is time since the beginning of the day.

initialize a time object
now = time(7,12,21,320000)

Just like the date object, the time object also has read-only attributes to get the key parameters.

time object read only attributes
now.minute

Also, similar to the data object, the time object also has replace methods and formatting methods.

time object replace method
now.replace(minute = 24)
datetime.time(7, 24, 21, 320000)

from datetime import time

now     = time(5,8,7)

print ( now )
Question – Execute the code above and select the correct output from the choices below. (The format is hours : minutes : seconds )
07:08:05
05:08:07

Time Object

This is a different time object compared to the one above. It is not part of the datetime module, but deserves a mention here. Every computer measures time in seconds since a starting point. Typically, its 1970. The time ( ) functions gives the number of seconds since.

import time 
time.time() 
1554191293.7841094 

This simple function can be pretty useful in python programs, specifically to calculate how long it takes for a piece of code to execute.

before = time.time() 
sum = 0 
for i in range(10000000) :     
    sum = sum + i 
after = time.time() 
time_taken = after - before 
time_taken 
1.8726410865783691 

OK.. That was summing up 10 million numbers and it took 1.8 seconds. What if we increase it to a billion ?

before = time.time() 
sum = 0 
for i in range(1000000000) :     
    sum = sum + i 
after = time.time() 
time_taken = after - before 
time_taken 
179.86842107772827 

Almost a 100 times. Looks correct.  

The time object also has a function that can return the local time, broken down into year, month, day, hour… etc.

struct_time structure
import time

print (time.localtime())
time.struct_time(tm_year=2019, tm_mon=12, tm_mday=17, tm_hour=14, tm_min=57, tm_sec=31, tm_wday=1, tm_yday=351, tm_isdst=0)

Datetime Object

datetime object contains info on both date and time.

import datetime 
datetime.datetime.now() 
datetime.datetime(2019, 4, 2, 13, 58, 20, 428414) 

That’s year,month, day,hour,minute,seconds, microseconds. You can very well construct a datetime object using the same parameters.

now = datetime.datetime(2019, 4, 2, 13, 58, 20, 428414) 
datetime.datetime(2019, 4, 2, 13, 58, 20, 428414) 

Of course, you can also extract all of the info back from the datetimeobject.

now.day 
2 

Of course, you can also extract all of the info back from thedatetime object.

and similarly

  • now.month
  • now.year
now.hour 
13

and similarly

  • now.second
  • now.microsecond
  • now.microsecond

you can even extract specific dateand time objects.

now.date() 
datetime.date(2019, 4, 2) 
now.time() 
datetime.date(2019, 4, 2) 

A simple example where you can apply this is if you are writing a event management app or a calendar app. For example, on top of other things related to the event, one of the key parameters is the start date/time and end date/time.

Another interesting use of datetime is to extract date and time from text and use it to do intelligent analysis. To extract text and convert it into date or time objects, you can use the strptime function of datetime object.

For example, if you have a text column in a dataset that contains date in the format JAN-01-1980, you can use the strptime function as follows.

from datetime import datetime  
d = "JUN-15-1980" 
date = datetime.strptime(d, "%b-%d-%Y") 
datetime.datetime(1980, 6, 15, 0, 0) 

Once you have the date string into the datetime object, lot of information can be extracted just from this date+time object. For example, day of the week . In time series analysis of stocks, this would be useful in analyzing which days of the week have higher trade.

now.weekday()
1
  • 0- monday
  • 1- tuesday
  • ..

Challenges

Challenge : Add 7 days to the current day

Create a date object either explicitly or using the today () function and add 7 days to it.
code
from datetime import date, timedelta

today = date.today ()
today_7 = today + timedelta(days = 7)

print ( today, today_7)

Challenge : Add 7 seconds to the current time.

Create a time object either explicitly or using the time () function and add 7 seconds to it.
code
from datetime import datetime, time

now = datetime.now ()
now_7 = now + timedelta(seconds = 7)

print ( now, now_7)

Challenge : Get the current week number of the year.

There are 52 weeks in a year. For example, Jan 2nd will be the first week of the year. So, get today’s date using the date object and display the current week number.
code
from datetime import datetime, time

now = datetime.now ()
current_week = now.isocalendar()

# tuple of year, week number, week day
print ( current_week)

Challenge : Add 1 year, 2 months and 3 days to the current date

Get today’s date using today ( ) and add the above mentioned timedelta to it. Note: There is no provision to add years or months using timedelta.
code
from datetime import datetime, timedelta

now = datetime.now ()
now_new = now

# add one year
now_new = now_new.replace ( year = now.year + 1)

# add two month
year  = now_new.year
month = now_new.month + 2

if month &amp;gt; 12 :
    year  = year + 1
    month = month - 12

now_new = now_new.replace ( year = year, month = month)


# add 3 days
now_new = now_new + timedelta(days = 3)

    
print ( now , now_new)

Challenge : Get all the dates of sundays in the current year

Say you are designing an event calendar. You want to identify all the days in a year where you can celebrate a particular event that can only be held on a sunday. Identify and Print all the dates in the current year where the day is a sunday.
code
from datetime import date, timedelta


#get the first sunday in the year
today = date(date.today().year,1,1)
today.weekday()  # monday = 0, tuesday = 1...
sunday = today + timedelta(days = 6 - today.weekday())

while ( sunday.year == today.year) :
    sunday = sunday + timedelta(days=7)
    print ( sunday )

Challenge : Print the number of days in February across all the years starting 2000 till date.

The number of days in February varies based on the year ( leap year or not ). Loop through all the years starting 2000 till the current year and print the year and the number of days in the February month of that year.
code
from datetime import date, timedelta

# we are not using the leap year method.
#Rather, we are iterating over each day and finding out the total number of days. 
#This is definitely not efficient, but will make you understand the process.

# get the date for feb month of 2000
feb = date(2000,2,1)

for year in range(2000,date.today().year + 1) :
    month = feb.month
    
    count = 1
    for i in range(1,31) :  # at most 31 days  
        feb = feb + timedelta(days = 1)
        
        # as long as we are still in feb
        if feb.month == month : 
            count = count + 1
    
    # print out the count
    print ( year, count)
    
    # add one year 
    feb = feb.replace( year = feb.year + 1)
    
    # and reset the date to 1st of feb
    feb = feb.replace(month = 2, day = 1)
    

Challenge : Print your name 10 times with a delay of 1 second.

execute the print statement 10 times with a delay of 1 second in between. Use the sleep function of the time module.
code
import time

for i in range(10) : 
    print ( "Ajay Tech") 
    time.sleep(1)

    

Challenge : There is a month long beer fest happening. Every 3rd day, there will be a rock concert. Identify all those dates.

Assume that the fest starts today, identify all the dates when the rock concert will happen.
code
from datetime import date, timedelta

today   = date.today ()
today_7 = today

today.day + 30

while today_7 &amp;lt;= today + timedelta(days=30) : 
    today_7 = today_7 + timedelta(days = 3)
    print (today_7)