Working with Time and Date in Python

Arturas Vycas
Geek Culture
Published in
6 min readSep 15, 2021
Photo by Towfiqu barbhuiya on Unsplash

One of the things I have to do quite often is to deal with various forms of data that includes time. I think that it is beneficial for everyone to understand how to manipulate this information as sometimes it is mandatory to do changes to your time or date format. For example, you might be analyzing time series data from temperature or humidity sensor, or you might be looking at some company sales report information, or you are taking notes on your personal expenses. Use case actually does not matter, you will always have to deal with time and date to represent information correctly which happened at some point in time. So in this article I am going to share some most common operations on time and date manipulation which you can do in Python.

Get current Time and Date

To start working with Time and Date in python, you need to import datetime module into your code:

import datetime

Now, you can easily get current time and date

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

During the time of running this example, I received a response provided below:

Output:

2021-09-12 22:11:15.327779

As you can see, returned response has a format of Year-Month-Day Hours:Minutes:Seconds.Milliseconds. It is important to note that now() method returns a time local date and time, so that totally depends on your location. Also, you can pass a timezone parameter to now() method, so you can receive time and date in UTC, for example.

Output:

2021-09-12 22:19:38.959631
2021-09-12 19:19:38.959631+00:00

So as you can see in my case, UTC time is 3 hours less than my local time.

Most of the time you don’t need to have millisecond information, so you can just drop using split() method. Important to note is that object returned by datetime.datetime.now() is a datetime class, so you have to convert it to a string if you want to apply split().

current_time_without_ms = str(datetime.datetime.now()).split('.')[0]
print(current_time_without_ms)

During the time of running this example, I received a response provided below.

Output:

2021-09-12 22:30:17

The reason why you need [0] in the code example above is because after applying, split(), the response will be a list of string objects. As in this case, the result was as provided below.

Output:

['2021-09-12 22:30:017', '193881']

So we only need the first element from this list.

Retrieving separate data fields

Now using the same current_time object, we can retrieve various fields separately. I think the code below is self explanatory. Note that result printed is using python f-string, which requires some string formatting to show result nicely. Code example is provided below.

Output:

2021-09-13 18:06:04

Working with timestamp

Another thing which you can encounter is Unix timestamp. You can also hear a few different names for that, one quite common is Posix timestamp, but that actually means the same. It is quite common in IoT industry for various devices to send timestamp information to servers instead of pure date and time as it takes less space. So Unix timestamp is simply the number of seconds passed since 00:00:00 UTC, January 1st, 1970. Knowing this is enough to deal with timestamps in Python.

So for example, you want to convert 2021–09–10 16:54:23 UTC time to a timestamp?

Output:

1631292863.0

Now if you want to do the conversion to time and date, you can do that by using fromtimestamp() method:

Output:

2021-09-10 16:54:23+00:00

As you can see it is quite straightforward to work with timestamps using datetime module.

There is actually a cool website which I use a lot when I am dealing with timestamps. You can convert time and date to a timestamp and vice versa and do a few more things. You can always double check if your calculations are correct: https://www.epochconverter.com/

Calculating time difference

Another quite common thing to is to find out what was the date and time in the past (or what will be in the future) if we substract or add some sort of value to our time object. That is were timedelta() method comes into action. So lets say, you have a certain date, for example 2021–08–10 17:45:00 and you want to know, what date and time would be in the future or was in the past if you add or substract certain amount of days, hours etc. The following code example demonstrates how it is done.

Output:

2021-08-06 15:32:00
2021-08-12 21:07:00

strptime() method is used to create a datetime object from string which holds time and date information, start_time_and_date in this case.

So you can do it like this if you want to know the exact date and time, but what if you want to know the difference, lets say in days/hours/minutes seconds between two dates, or timestamps? This can also be achieved. Lets take results from previous example and find what is the difference between 2021–08–12 21:07:00 and 2021–08–06 15:32:00

Output:

6 days, 5:35:00

As you can see, we have easily calculated difference between two datetime objects.

Understanding strftime() and strptime() methods

Last thing I want to talk about here are these two methods. They are provided within datetime module and their use is to conveniently convert datetime objects to strings and vice versa. Now I am not going to dive deeply in all formatting possibilities, but they are described really good in python documentation, which can you find in the article below:

Anyway, I will show you a few examples. So suppose you need to create a datetime object having a date string. Now these strings can have various formats, and that is why you need a formatting string, so that datetime module could parse correctly your input. Below example illustrates the usage of strptime() method

Output:

2021-08-06 16:00:00
2021-08-06 16:00:00
2021-08-06 16:00:00
2021-08-06 16:00:00
2021-08-06 16:00:00

As you can see from the example, output is identical in all cases. That is because we supplied exact format of our date and time string to strptime().

Now we can reverse this and use the same logic with strftime() which will allow us to get a string from datetime object. For better visual understanding, I will use the same 2021–08–06 16:00:00 value

Output:

2021-08-06 16:00:00
2021/08/06 16/00/00
06 August 21 - 16:00:00
06 August 21 - 04 PM
Aug 2021, 06 / 04 PM

There are other formatting options which you can look for in the documentation link which I have provided above, but I hope you that you should be able to get the idea how these two methods work and how and when you should use them.

Conclusion

Working with Time and Date is a very common task in python. This tutorial shows the basics you need to understand how to use datetime module in python to make your life easier when working with timeseries data on your day to day tasks.

I have uploaded all examples used here to my github repository. One thing I would like to mention that actually this module is called datetime. But the class used is also called datetime. That is why in the code you will see

import datetime as dt
from datetime import datetime

What this allows to do is to access datetime class methods more conveniently, so for example instead of current_time = datetime.datetime.now() you can write current_time = datetime.now()

Hope that is not too confusing, but I will be happy to answer the questions if you have any.

Link to the github repository with all examples in one place: https://github.com/vycart/datetime_tutorial

Thank You for Reading.

--

--

Arturas Vycas
Geek Culture

Embedded Software Engineer, Python enthusiast. I love to share knowledge and learn new things.