Date and Time
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
- Date Object
- Timedelta Object
- How many days till my next birthday
- datetime.time Object
- Time Object
- Date Time Object
- Challenges
There are 4 key objects in Python’s datetime module. Depending on the requirements, you can select the appropriate object.

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.

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.

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

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

from datetime import date
today = date(2019,12,01)
print ( today.strftime("%b '%y"))
from datetime import date
today = date(2019,1,18)
print ( today.strftime("%W"))
from datetime import date
today = date(2019,1,7)
yesterday = date(2019,1,6)
print ( yesterday-today)
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 ?

from datetime import date
today = date(2019,1,7)
yesterday = date(2019,1,6)
type(today - yesterday)
from datetime import date
today = date(2019,1,7)
yesterday = date(2019,1,6)
today < yesterday
from datetime import date, timedelta
today = date(2019,1,7)
print ( (today - timedelta(days = 2)).day )
from datetime import date, timedelta
today = date(2019,3,7)
print ( (today - timedelta(months = 2)).month)
from datetime import date
today = date(2019,1,7)
yesterday = date(2019,1,6)
print ( (yesterday - today).days )
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.

now = time(7,12,21,320000)
Just like the date object, the time object also has read-only attributes to get the key parameters.

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

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

from datetime import time
now = time(5,8,7)
print ( now )
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.

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
codeChallenge : Add 7 days to the current day
Create a date object either explicitly or using the today () function and add 7 days to it.
from datetime import date, timedelta today = date.today () today_7 = today + timedelta(days = 7) print ( today, today_7)
codeChallenge : Add 7 seconds to the current time.
Create a time object either explicitly or using the time () function and add 7 seconds to it.
from datetime import datetime, time now = datetime.now () now_7 = now + timedelta(seconds = 7) print ( now, now_7)
codeChallenge : 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.
from datetime import datetime, time now = datetime.now () current_week = now.isocalendar() # tuple of year, week number, week day print ( current_week)
codeChallenge : 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.
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 &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)
codeChallenge : 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.
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 )
codeChallenge : 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.
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)
codeChallenge : 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.
import time for i in range(10) : print ( "Ajay Tech") time.sleep(1)
codeChallenge : 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.
from datetime import date, timedelta today = date.today () today_7 = today today.day + 30 while today_7 &lt;= today + timedelta(days=30) : today_7 = today_7 + timedelta(days = 3) print (today_7)