Python Date and Time

In this tutorial you will master to handle the date and time in python with the help of examples. You will walk through different modules used to manipulate date and time ,how to read and print time in a specific format ,etc.

Facts  about Date and Time

Before digging deep into working of date and time let's walk through some old days to know about how computers count the time. Pointing to the fact, almost all computers are counting time based on Unix Epoch time which is 00:00:00 UTC on 1 January 1970.UTC (Coordinated Universal Time ), often known as GMT( Greenwich Mean Time) refers to the time of  longitude at  0°.

Like other programming languages ,python too embraces the Unix Time concept whose standard library comprises a  popular module named time. The time module got a function called time() which outputs the number of seconds since the unix epoch time.

>>> import time
>>> time.time()
1599329118.616698 

This Unix time representation is incredibly difficult for humans to parse,hence it needs another way to convey the time to users. It can be accomplished by converting the Unix time to UTC which again converts to local time with the help of time zone offsets.the database of all values for the timezone offset is maintained by the Internet Assigned Numbers Authority in short known as IANA.

Date and Time Standardization

Since it was difficult for humans  to determine the time in seconds, the time format was calculated in terms of years ,months,days, hours and so on. The world we live in is filled with diversity  in every aspect like geographically , linguistically , culturally etc. so it became a necessity to standardize the time format to steer clear of all unnecessary complexity and communication mistakes. The International Organisation for Standard brings up ISO -8601 which specifies the date format should be in the order of most significant to least significant data. To be clear the standardized date format is as follows:

YYYY-MM-DD HH:MM:SS 

Where YYYY denotes the year in four digit ,MM and DD gives the two digit representation of Month and Day. Similarly HH,MM and SS represents the two digit form of hours, minutes and seconds.

The key benefit of this is to avoid the ambiguity of date formats. For instance MM-DD-YYYY or DD-MM-YYYY oftenly misinterpreted when the value of month is a valid number.

Python date and time modules

Python offers three distinct modules to work with Date and Time . They are listed as follows:

  1. Calendar module
  2. Datetime module
  3. Time module

Let’s start our learning with module datetime which helps to manipulate both date and time in python.

Constants in Datetime Module

Get the minimum and maximum year represented in a system can be exported using the two constants MINYEAR and MAXYEAR in the datetime module.
The MINYEAR returns the smallest year number allowed in date and datetime objects, which is 1 while the MAXYEAR gives the largest  year number  representation permitted in date and datetime objects which is 9999.

import datetime

#constants in datetime Module
import datetime
print(datetime.MINYEAR)
print(datetime.MAXYEAR) 
1
9999

Classes in Datetime Module

To manipulate the date and time , Python datetime module contains the following classes which are tabulated here.

Class Returns or Description Attributes
datetime.date An idealized date Year, month and day
datetime.time An idealized time Hour,minute,second, microseconds and tzinfo
datetime.datetime Date and time combination Year,month,day,hour, Minute,seconds, microseconds and tzinfo
datetime.timedelta Duration between two instances Weeks,days,hours,minutes,seconds,microseconds, milliseconds,
datetime.tzinfo Timezone information Nil
datetime.timezone Implements tzinfo abstract base class Nil

The objects of classes date,time,datetime and timezone are immutable and hence hashable. So these objects can be used as a key for a dictionary.

Python Date Objects

Date objects in python work with dates in an idealized Gerogian calendar. It represents a date in the standard form YYYY-MM-DD.

datetime.date(year,month,day) 

Here the arguments are must and should be an integer with their stipulated ranges as follows:

  • Year must between 1 and 9999 inclusive
  • Month must  between 1 and 12 inclusive
  • Day must be between 1 and 31inclusive , depends on year and month.

If any of the arguments failed to meet these range specifications ,then it encounters a ValueError.

How to get Date

  1. Using today() method

    The method today() is used to get the current local date.In this example we have imported the module datetime and we have created an object d_ob for the class datetime.date which calls the method today().

    import datetime
    
    #Current date
    d_ob = datetime.date.today()
    print(d_ob) 
    
    2020-09-06
    

    The result provides you the current local date.

  2. Using fromtimestamp() method

    Unix timestamp is the time represented in the number of seconds between a specific date and January 1, 1970.for instance 1599468233 is a timestamp. It is possible to convert a timestamp to actual date with the help of a method called fromtimestamp().

    from datetime import date
    ts = date.fromtimestamp(1599468233)
    print('Date from Timestamp is',ts) 
    
    Date from Timestamp is 2020-09-07 
    
  3. Using fromisoformat() method

    A date given in the form of string can be converted into standard format using the method fromisoformat(). This is a pretty cool method which always outputs the date in the format YYYY-MM-DD.

    from datetime import date
    str = date.fromisoformat('2020-02-14')
    print(str) 
    
    2020-02-14
    
  4. Using fromisocalendar() method

    The method fromisocalendar gives you the date when year ,week and day is passed as the argument .

    from datetime import date
    cal_date = date.fromisocalendar(year=2020,week=20,day=5)
    print(cal_date)
    
    2020-05-15
    

Python datetime objects

Now suppose if you want to get the current date along with time you can use the other class in the datetime module which is datetime.datetime.A datetime object is an individual object which works with date object and time object.

 datetime.datetime(year,month,day,hour=0,minute = 0,sec = 0,tzinfo = None)


The commonly used methods are listed below :

  1. now() method for current date and time

    Datetime class invokes the method now() as shown in the below example to get the current local date and time.
    import datetime
    
    #Current date
    dt_ob = datetime.datetime.now()
    print(dt_ob)
    

     

    2020-09-06 15:39:27.272038
    
  2. today() method for current date and time

    import datetime
    
    #Current date
    dt_ob = datetime.datetime.today()
    print(dt_ob)
    

     

    2020-09-06 15:39:27.272038
    

    You can also instantiate the datetime classes by passing keyword arguments as given in the example: The only difference is that here we are not invoking any specific methods rather we provide the date and time.

    from datetime import datetime
     dt_ob3 = datetime(year = 2020,m = 29,hour = 6,minute = 30,sec
    print(dt_ob3)
    

     

    2020-10-29 06:30:45
    

    It is also possible to retrieve individual entities like year alone or month alone or hour alone. This can be accomplished with dot notation.

    from datetime import datetime
     dt_ob = datetime(year = 2020,m = 29,hour = 6,minute = 30,sec
    print('Current Year is',dt_ob.year)
    print('Current time is ',dt_ob.hour)
    print('Timestamp of the date is',dt_ob.timestamp())
     
      
    Current Year is  2020
    Current Minute is 6
    Timestamp of the date is 1603938645.0
    
  3. Using fromtimestamp() method

    from datetime import datetime
    ts = datetime.fromtimestamp(1599468233)
    print('Date from Timestamp is',ts)
    

     

    
    Date from Timestamp is 2020-09-07 12:43:53
    

What is timedelta class in python

Timedelta class is  a class commonly used in datetime modules along with aforementioned classes  to find the difference of two dates or time i.e the duration. In the following example we have created two date objects d1 and d2 and their difference is stored in d3. Here, d3 belongs to the timedelta class. Similarly the difference of two datetime objects gives you a timedelta object.

from datetime import date,time,datetime

from datetime import date,time,datetime
d1= date(2020,9,2)
d2=date(2019,9,7)
d3 =d1-d2
print('Difference is ',d3)
print("Type is ",type(d3))

t1=datetime(2020,9,2,11,45,30)
t2=datetime(2018,9,7,10,50,40)
print('time Difference is ',(t1-t2)) 

Output:


Difference is  361 days, 0:00:00
Type is  <class 'datetime.timedelta'>
time Difference is  726 days, 0:54:50

How to Manipulate two timedelta Objects

To manipulate timedelta objects we initially need to import the timedelta class from the datetime module.

#timedelta objects difference
from datetime import timedelta
td1 = timedelta(weeks=2,days=3)
td2 = timedelta(weeks=1,days=5)
td3 = td1-td2
print(td3)

 

5 days, 0:00:00

Negative timedelta object

#timedelta objects difference
from datetime import timedelta td5 = timedelta(sec
td  = timedelta(sec
td7 = td5-td6
print(td7)
print(abs(td7))

-1 day, 23:59:30

Timedelta objects in seconds

To get the timedelta objects in seconds we can use the method called total_seconds() which expresses duration in seconds.

from datetime import timedelta

td1 = timedelta(weeks=2,days=3)
print(td1.total_seconds()) 

 

1468800.0

Python datetime formatting

We have discussed earlier that in different countries the format of date and time differ. For instance in the US the common date format they rely on is MM-DD-YYYY whereas in the UK the format is DD-MM-YYYY. This creates an ambiguity if the month is a valid number. So a measure to handle this ambiguity is required in python, so here comes the two formatting methods:

strftime()

Strftime method() is a formatting method defined in all three classes(date,time,datetime) to represent a given date,time and datetime as readable string.it contains only one argument called format where we specify the format in which date is needed.

visualization below gives you better clarity on the concept.

strptime

Example of strftime() method


from datetime import datetime

t = datetime.today()
print(t)

f1 = t.strftime("%m/%d/%Y, %H:%M:%S")
# MM/DD/YYYY H:M:S format
print("Format 1:", f1)

f2 = t.strftime("%d/%m/%Y, %H:%M:%S")
# DD/MM/YYYY H:M:S format
print("Format 2:", f2)

Output:


2020-09-27 16:15:36.913768
Format 1: 09/27/2020, 16:15:36
Format 2: 27/09/2020, 16:15:36

strptime()

This is another formatting method which is supported by datetime objects only and is just the opposite of strftime() method. Here the datetime object gets created from the given string. And it contains two arguments

  1. A string of date and time (‘02-14-2020’)
  2. Format for the string (%d/%m/%Y)

On the basis of the above two arguments it produces a datetime object as the result. The following visualization clears the idea.

strptime

Example of strptime() method

from datetime import datetime

Str = "June 5,2020"
print(Str)

dt_ob=datetime.strptime(Str,"%B %d,%Y")
print(dt_ob)

 

Output:

June 5,2020
2020-06-05 00:00:00

Value Error in strptime()

When the string and the format code passed  to the strptime() method does not match, python will raise a ValueError For instance,


from datetime import datetime

Str = "June 5,2020"

dt_ob=datetime.strptime(Str,"%d %B ,%Y")
print(dt_ob)

 

Output:

ValueError: time data 'June 5,2020' does not match format '%d %B ,%Y'

Format codes for strftime() and strptime().

Directive Meaning Example
%a Abbreviated version of weekdays. Sun, Mon, …, Sat
%A Complete version of weekdays. Sunday, Monday, …, Saturday
%w Weekday as a decimal number, where 0 is Sunday ,1 is Monday and 6 is Saturday. 0, 1, …, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%b Abbreviated version of month Jan, Feb, …, Dec
%B Complete version of month January, February, …, December
%m Month as a zero-padded decimal number. 01, 02, …, 12
%y Short version of year excluding century 00, 01, …, 99
%Y Full version of year including century 0001, 0002, …, 2013, 2014, …, 9998, 9999
%H Hour as a zero-padded decimal number.- 24 hour 00, 01, …, 23
  %I   Hour as a zero-padded decimal number- 12 hour   01, 02, …, 12
%p AM or PM. AM, PM
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999
%z UTC offset in the form ±HHMM[SS[.ffffff]] (empty), +0000, -0400, +1030, +063415, -030712.345216
%Z Time zone name (empty), UTC, EST, CST
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week) as a decimal number. 00, 01, …, 53
%c date and time local representation. Tue Aug 16 21:30:00 1988
%x Date local  representation. 08/16/88 (None);08/16/1988 (en_US)
%X Time local  representation. 21:30:00
%% A literal '%' character. %