Manipulating Dates and Times in Python

Rate this post

In this article we will cover some basic features of the datetime module in Python. More specifically, we will see how to extract the current date and time and how to implement these features within a script in order to realize time-driven actions.

Long Story Short

The datetime module in Python allows you to deal with date and time expressions. By exploiting classes like .time() and/or .datetime() you can express times and dates in a dedicated format.

The class .timedelta() allows you to define a specific time duration interval and add it to a datetime expression.

The method .today() can be then used to extract the current time or/and datetime. You can then convert a specific time interval expressed with the .timedelta() class into seconds y exploiting the method .total_seconds().

Finally, if you want to extract the microseconds amount from a time expression, you can easily achieve the result by using the method .microsecond().

The datetime Module

The datetime module contains multiple classes, the most famous and used are:

  • .time – it gives as output an idealized time in the format hours : minutes : seconds
  • .datetime – gives as output a combination of a date and a time in the format year - month - day hour : minutes : seconds
  • .timedelta – expresses a duration, indicated as the difference between two dates, times or datetimes.

The following code lines provide an example of these three classes.

import datetime

# express a time
print(datetime.time(10, 23, 45))
# 10:23:45

# express a date and time
print(datetime.datetime(2019, 2, 3, 10, 23, 45))
# 2019-02-03 10:23:45

# add to a date and time a specific duration
time1 = datetime.datetime(2019, 2, 3, 10, 23, 45)
delta = datetime.timedelta(days=4, hours=3)
time2 = time1 + delta
print(time2)
# 2019-02-07 13:23:45

As you can see in the example, it is possible to express times and dates in a dedicated format by exploiting the module datetime and its two classes time and datetime, respectively.

We then defined a specific date and time and assigned their values to the variable “time1”. We then define a time duration (i.e. 4 days and 3 hours) and assign it to the variable “delta”; finally, we obtain the expression for the date and time corresponding to “time1” after an amount of time equal to “delta” has passed.

Please note when defining the .timedelta(), we used the arguments days and hours; in a similar way, we could have also specified other intervals by using all the available arguments for this function (see the official documentation).

Get the Current Date and Time with .today()

In the case we want to get the current time and/or the current date, we can exploit the method .today(); it can be applied to both the date and datetime classes and it will return the current date and the current date and time (at the microsecond precision), respectively. The following code lines show an example of how it works.

#get current date
current_date = datetime.date.today()
print(current_date)
# 2021-04-10

#get current date and time
current_dt = datetime.datetime.today()
print(current_dt)
# 2021-04-10 15:17:12.641393

Express a Duration in Seconds with .total_seconds()

In some applications it might be useful to express a specific amount of time in seconds, without using the hours : minutes : seconds notation.

Let’s take, for example the duration that we applied in the previous section: it was 4 days and 3 hours in total. If we want to obtain the respective number of seconds that corresponds to this period of time, we will just have to type:

# Get the duration in seconds
print(delta.total_seconds())
# 356400.0

You can also verify that 356400.0 is the correct answer by making the conversion manually, which would be: 4(days) * 24(hours) * 60(minutes) * 60(seconds) + 3(hours) * 60(minutes) * 60(seconds) = 356400.

Extract the Microseconds Value from the Time Notation with the .microsecond Attribute

Sometimes we might be interested in obtaining the number of microseconds that have passed from a specific instant of time. In this case, we would have to extract from the whole time expression, just the part that is indicating the microseconds. In order to do that, we can use the attribute .microsecond, which gives as output an integer number, corresponding to the microseconds elapsed in the indicated time.

# extract the microseconds from the current time
current_microsec = datetime.datetime.today().microsecond
print(current_microsec)
# 641393

Please note that the method .microsecond just extracts the corresponding microseconds number from a specific time definition; it does not convert a time duration into microseconds.

Now that we have familiarized with some of the functions for handling the date and time in Python, we will see through a practical example, how to exploit the above explained features to perform time-controlled operations within a Python script.

Put Your Script Asleep and Wake It Up Every Three Seconds

In this example we will see how to handle the time within a script and how to use the above-mentioned functions to put the script asleep for some seconds. This is a crucial thing in lots of applications where “heavy” tasks have to be performed or in cases where your script has to run for long periods of time and you do not want your system to be active for the whole script duration.

We start by obtaining the current date and time using the method .datetime.today(), then we define a time interval of three seconds by exploiting the method .timedelta(). After this, we define a future date and time instant, called “future”, which is obtained by summing the three seconds time interval to the initial time.

# make the script sleeping for some time
t = datetime.datetime.today()
delta = datetime.timedelta(seconds=3)
future = t + delta

Now we need to create a for loop, in order to perform multiple iterations (in this example we will iterate three times) in which we will “put the script asleep and wake it up” alternately.

We define the duration of the sleeping time by converting the 3 seconds time interval into seconds; it may sounds dumb (and in this case it is) but if we were to choose a longer time interval, like days, we would have had to obtain the interval duration expressed in seconds, and also, we need it to be an integer number, not expressed in time notation.

To put the script asleep, we exploit the method .sleep(), from the time module. This method accepts as input an integer, corresponding to the number of seconds we want our system to be asleep. When the 3 seconds have passed, we print the current time with a sentence saying that 3 seconds have actually passed from the previous iteration. 

import time

for i in range(3):
    # sleep for the time difference between the initial time and the future (in sec)
    time.sleep(delta.total_seconds())
    print("It's " + str(datetime.datetime.today()) + " 3 sec have passed")

'''
   It's 2021-04-11 11:42:33.767437 3 sec have passed
   It's 2021-04-11 11:42:36.777588 3 sec have passed
   It's 2021-04-11 11:42:39.787928 3 sec have passed
'''

Conclusion

In this article we learnt how to deal with time and date notations in Python and how to use these features within a script. We explored different modules and methods for obtaining the current time, date and also for calculating time intervals (and more!). In the end, we exploited these functions to write a short script which allowed putting asleep the system for a specific amount of time and waking it up at precise time intervals. This example can be extremely useful when designing scripts that have to run for long periods and we do not want to keep the system active for all that time.