Sea of Tranquility    About    Archive    Feed

Handling date and time in Python

The datetime module

The datetime module provides the following classes for processing date and time information.

  1. date
  2. time
  3. datetime
  4. timedelta
  5. tzinfo

The syntax for importing the classes is from datetime import <class>.

For example, the datetime module can be imported by the following command.

from datetime import datetime

The datetime.datetime type

The first datetime is the module name. The second datetime is a type defined in the module. This is a class which has

  • attributes
  • datetime objects
  • instance methods

The datetime objects have the following attributes:

  1. year
  2. month
  3. day
  4. hour
  5. minute
  6. second
  7. microsecond and
  8. tzinfo.

To create a datetime object, it’s not necessary to provide all the attributes.

  • A datetime object can be created by providing only year, month, and day
  • If not specified, hour, minute, second, and microsecond are set to zero
  • If not specified, tzinfo is set to None

datetime.today() returns the current date and time - upto microsecond. today() is one of the datetimeobjects.

The statement t1 = datetime.today() creates an instance of datetime.today() and assigns it to the variable t1.

t1 = datetime.today()
t1

Output:

datetime.datetime(2020, 2, 14, 12, 37, 35, 317779)

The individual attributes of a datetime object, like year, month etc can be accessed using the dot notation.

print("Year:", t1.year)
print("Month:", t1.month)
print("Day:", t1.day)
print("{}".format(t1.strftime('%A'))) ## See next section for an explanation

Output:

Year: 2020
Month: 2
Day: 14
Friday

Finding day of the week

The day of the week can be found by using the instance method weekday(). It returns an integer in the range 0 to 6 (both included), where 0 corresponds to Monday, 1 corresponds to Tuesday, and so on.

print(t1.weekday()) ## 4 corresponds to Friday

Output:

4

This returns an integer that corresponds to a day of the week. If we want to display the actual name of the weekday, we have to use the strftime() method. As you will see, it reurns the string values corresponding to the integer values returned by datetime objects.

Formatting dates and times

As you might have noticed, the datetime module returns only integer values even for day of the week and month. However, in many cases, we want the actual names to be displayed like “January”, “Monday” etc. The strftime() method provides us a means to display datetime objects in multiple formats using certain codes. The list of codes is give below.

  • Formatting year
    • %y - Last two numbers of the year e.g. 20
    • %Y - Full year e.g. 2020
  • Formatting month
    • %b - Month abbreviation e.g. Jan, Feb
    • %B - Month full name e.g. January, February
  • Formatting day
    • %d - Day of the month as a zero-padded integer e.g. 01, 02
    • %a - Weekday as abbreviated name e.g. Mon, Tue
    • %A - Weekday full name e.g. Monday, Tuesday
  • Formatting hour, minute, and second
    • %H - 24-hour clock
    • %h - 12-hour clock
    • %M - Minute as zero-padded decimal
    • %S - Second as zero-padded decimal
    • %p - Time in AM/PM format

Examples:

eclipse_time = datetime(2020, 6, 21, 10, 24)
print("The next solar eclipse visible from India is on {}.".format(eclipse_time))
print("The next solar eclipse visible from India is on {}.".format(eclipse_time.strftime('%b %d, %Y')))
print("The next solar eclipse visible from India is on {}.".format(eclipse_time.strftime('%A %B %d, %Y')))
print("The next solar eclipse visible from India is at {}".format(eclipse_time.strftime('%H:%M %p')), "on {}.".format(eclipse_time.strftime('%A %B %d, %Y')))

Output:

The next solar eclipse visible from India is on 2020-06-21 10:24:00.
The next solar eclipse visible from India is on Jun 21, 2020.
The next solar eclipse visible from India is on Sunday June 21, 2020.
The next solar eclipse visible from India is at 10:24 AM on Sunday June 21, 2020.

Comparing datetime objects

datetime objects can be compared like using the standard operators. Between two dates, the older one is considered to be lesser. For exacmple, your previous birthday is lesser than your current year’s birthday.

bday_previous = datetime(2019, 6, 8) #Creating a datetime object for your birthday in 2019
bday_current = datetime(2020, 6, 8) #Creating a datetime object for current year's birthday

bday_previous < bday_current

Output:

True

To compare two datetime objects, Python compares the values of the individual attributes until the given condition is true.

As an example, let’s compare two datetime objects with the following attribute values. We want to know if t1 is less than t2.

t1 = datetime(1985, 1, 1, 11, 22, 45, 0)
t2 = datetime(1985, 1, 1, 11, 23, 45, 100000)

t1 < t2

Output:

True

Checking for this condition involves the following steps.

  1. Compare year values. They are equal. Move to month.
  2. Compare month values. They are equal. Move to day.
  3. Compare day values. They are not equal and t1.day < t2.day
  4. Halt

The condition we want to check is satisfied in the day attribute, and the program execution stops there. The rest of the atrributes are not even considered.

This method works for comparing date and time values only if the attributes are arranged in the order:

year, month, day, hour, minute, second, microsecond.

Finding elapsed time

A datetime object represents a particular instant of time, upto a microsecond. We can find the duration between two time instants by finding the difference between their corresponding datetime objects. Interestingly, this operation returns a value that is of type timedelta. Yes, you read it right:

Subtracting one datetime object from another datetime object returns a timedelta object.

datetime1 - datetime2 = timedelta

t2 - t1

Output:

datetime.timedelta(0, 60, 100000)

Note that we can get the elapsed time only in terms of days, seconds, and microseconds. This is because, timedelta objects have only three attributes, and they are,

  1. days
  2. seconds
  3. microsecond

To drive this point home, let’s consider a different example.

t3 = datetime(1990, 6, 8)
t4 = datetime.today()
delta_t = t4 - t3
delta_t

Output:

datetime.timedelta(10843, 36913, 818363)

t4 - t3 returns the elapsed time since June 8, 1990, 00:00:00. Specifically, it returns elapsed days, seconds, and milliseconds. If you try to directly pull out the number of years since t3, you will get an error because year is not an attribute of a timedelta object.

delta_t.year

Output:

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-12-bb65e368b0e0> in <module>
----> 1 delta_t.year


AttributeError: 'datetime.timedelta' object has no attribute 'year'

However, it’s easy to pull out the days, seconds, microseconds values.

print(delta_t.days)
print(delta_t.seconds)
print(delta_t.microseconds)

Output:

10843
36913
818363

While two datetime objects can be subtracted from each other, there is no provision to add two datetime objects. However, we can add a timedelta object to a datetime object.

Given below is a summary of operations supported by datetime objects.

  1. Two datetime objects can be compared using relational operators
  2. Two datetime objects can be subtracted from each other. This returns a timedelta object
  3. A datetime object can be added to a timedelta object. This returns a datetime object
  4. Two datetime objects can not be added

References

  1. Allen Downey. Think Python. How to Think Like a Computer Scientist. Green Tea Press, Needham, Massachusetts
  2. Python 3.8.2rc1 documentation. https://docs.python.org/3/library/datetime.html#module-datetime. Accessed on February, 14, 2020.
  3. Katernya Koidan. How to work with Python Date and Time Objects. https://academy.vertabelo.com/blog/python-datetime-for-beginners/ Accessed on February 14, 2020.
  4. Time and Date. https://www.timeanddate.com/eclipse/in/india/dehradun?iso=20200621 Accessed on February 14, 2020