Get up to 80 % extra points for free! More info:

Lesson 14 - Datetime Library for Python

In this Python tutorial, we'll look at working with the datetime module, which, in addition to the time and calendar modules, is used to work with the date and time and supports a more pleasant, object-oriented approach.

Datetime

We must always import the datetime library at the beginning of the program:

import datetime

This library offers more object-oriented approach than the one we showed last time. It works with its own specialized datetime objects. This will allow us, for example, to easily subtract individual data from each other, or compare them with each other without having to deal with the number of seconds since 1970 or the indices in the tuple. We'll now show how these objects are created and how to continue working with them in individual modules.

datetime()

A very important class in this library is the datetime class of the same name and its datetime() method. We can use this to create instances that we'll work with further. It also provides useful methods that we'll use extensively.

Let's create an instance of a date and time from a specific year, month, and day:

import datetime

# datetime.datetime(year, month, day, hour, minute, second, microsecond)
d1 = datetime.datetime(2019, 11, 24)
print(d1)

If we want to use only the part of the library that's related to the datetime class, we can modify the import into a variant:

from datetime import datetime

d1 = datetime(2019,11,24)
print(d1)

Methods on datetime

Next, we will show several methods on the datetime class.

now()

The now() method simply allows us to get the current date and time:

import datetime

now = datetime.datetime.now()
print(now)

This method creates an instance of the datetime.datetime class mentioned before, in which we can find current information. We can get to the individual data very easily using the attributes year, month, day, hour, minute and second:

import datetime

now = datetime.datetime.now()

print("Date:")
print("Year: {}".format(now.year))
print("Month: {}".format(now.month))
print("Day: {}".format(now.day))
print("Time:")
print("{}:{}:{}".format(now.hour, now.minute, now.second))

weekday()

Again, we call the method on a pre-created instance. It finds out its day of the week. Let's try to call it on the current date and time, which we can already find out too:

import datetime

now = datetime.datetime.now()

#List of days of the week with indices
days_of_week={ 0:"Monday", 1:"Tuesday", 2:"Wednesday", 3:"Thursday", 4:"Friday", 5:"Saturday", 6:"Sunday" }

day = days_of_week[now.weekday()]
print("Day of the week: {}".format(day))

Here we have to pay attention to the correct indexing again: Monday = 0 - Sunday = 6.

strftime()

This method allows us to create a usable and easy-to-read date and time format for users:

import datetime

now = datetime.datetime.now()

text1 = now.strftime("%H:%M:%S")
text2 = now.strftime("Hours:%H, Minutes:%M, Seconds:%S")

text3 = now.strftime("Day:%d, Month:%m, Year:%Y")

print(text1)
print(text2)
print(text3)

When used, we must define what our desired output should look like in strftime(). 6 specific characters are used to indicate what to print. They are:

  • %d - day
  • %m - month
  • %Y - year
  • %H - hour
  • %M - minute
  • %S - second
  • %a - abbreviation of the day of the week
  • %A - day of the week
  • %w - day of the week - numeric value
  • %b - month abbreviation (not numeric)
  • %B - month (full name)

strptime()

strptime() function works in the opposite way. We insert the date and time in it, written in text form, e.g. entered by the user. Then we need to specify what format is used and the function returns a datetime instance:

import datetime

#Predetermined information
info = "25/5/2000 12:35"

date = datetime.datetime.strptime(info, "%d.%m.%Y %H:%M")
print(date)

There are many possibilities for us in this method, and it's up to us which format we choose to obtain the date and time.

Working With Data

The fact that we store everything as an instance of the same class brings us many benefits when working with data.

Arithmetic Operations

For example, we can perform basic mathematical operations with data, such as addition and subtraction:

import datetime

#Initialize current date
now = datetime.datetime.now()

#Initialize the date 1/1/2000
d2000 = datetime.datetime(2000, 1, 1)

d3 = now - d2000
print(d3)

In this case, the date d3 contains the number of days, hours, minutes and seconds that have elapsed from the beginning of the 3rd millennium to the present day. For a similar purpose, we can also use the function total_seconds(), which returns the number of seconds elapsed between the two intervals.

Comparison

We can also compare two dates with each other using ordinary operators, which we would use when comparing numbers:

import datetime

# Initialize current date
now = datetime.datetime.now()

# Initialize the date 1/1/2000
d2000 = datetime.datetime(2000, 1, 1)

print(now > d2000) # Returns True
print(now == d2000) # Returns False

timedelta

For other possibilities of working with time, there is timedelta. For example, if we subtract two dates, we get an instance of the datetime.timedelta class, which is not a specific date, but an interval (difference) between some two dates. We can also create this object ourselves. We can easily find out what day will it be in 10 days:

import datetime

# Current day
now = datetime.datetime.now()

print("Today's date: {}".format(now))

# timedelta object with a 10 day shift
td10 = datetime.timedelta(10)

d1 = now + td10
d2 = now - td10
print("Date in 10 days: {}".format(d1))
print("Date 10 days ago: {}".format(d2))

The timedelta() constructor does not always have to be used with whole days. If we want to work with a different value, we have the option. When creating a timedelta object, we can select many parameters:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

The timedelta instance has properties like days and more. Unfortunately, it does not have the number of years, because a year is not a full-fledged time unit and does not have a fixed number of days (some years are leap years). We'll do more about this issue in the exercise.

replace()

replace() method is also very useful. This, like timedelta(), allows us to change already created time objects. For example, let's increase the year and day on a datetime object by 1:

import datetime

# Current day
now = datetime.datetime.now()

r1 = now.replace(year = now.year + 1)
d1 = now.replace(day =  now.day + 1)

print(r1.date())
print(d1.date())

We can use the replace() method on any time object. In it we have to specify what we want to change (e.g. year = ...) and indicate to what value it should change. It's only a change of the value of an already created variable.

date()

All the methods we mentioned earlier work with datetime objects (date and time). If we want to use only the date, it's advisable to use the date object instead. It then doesn't have information about the date and time, which could otherwise make operations (e.g. comparisons) uncomfortable for us. We get the date object from the datetime object using the date() method:

import datetime

#Current day
now = datetime.date.today()

print("Today's date: {}".format(now))

d = datetime.date(2000, 12, 24)
print("Year: {}".format(d.year))
print("Month: {}".format(d.month))
print("Day: {}".format(d.day))

There is nothing complicated about it. The only change from datetime is to use the today() method, which directly replaces now(). All methods used above are fully compatible with this format. So if we don't need time information in our programs, we can get rid of it relatively easily.

In the next lesson, Type System and Type Hints in Python, we'll discuss how we can make the code more readable and easier to analyze using types.


 

Previous article
Magic Methods in Python - Collections and Descriptors
All articles in this section
Object-Oriented Programming in Python
Skip article
(not recommended)
Type System and Type Hints in Python
Article has been written for you by Shift
Avatar
User rating:
No one has rated this quite yet, be the first one!
As an author I'm interested mainly in industry automation. I'm also writing music and literature. In my spare time I'm working on a few games in Game Maker Studio.
Activities