How to Use Python Datetimes Correctly?

Datetime is basically a python object that represents a point in time, like years, days, seconds, milliseconds. This is very useful to create our programs.

The datetime module provides classes to manipulate dates and times in a simple and complex way. While date and time arithmetic is supported, the application focuses on the efficient extraction of attributes for formatting and manipulating output

Let's import the Python module

Creating a date using year, month, and day as arguments.

datetime(year, month, day hour, minute, seconds)

Now once we've created the object and assigned to the variable called birthday, we can access to each date format just like this

As you can see, it's very easy to create a date using this module. Now we can do other interesting things, like:

This means that the birthday was a Monday, because days are in this format (0-6), or what is the same indexed as a list (beginning with zero).

But what if I want to know what is the current datetime? In that case, we can use datetime.now(), Go ahead and write down this into next cell

Ok, that's interesting. What if you run that command again? Go ahead and see the difference

As you can see the output is now different, because time changed. Great! Now you can ask, how do I calculate the time from one date to another? That's called time tracking, let's see how it works

You can see, how easy it is, we can run arithmetic operations between dates, which is great! But what if now you want to know how much time has passed from a given date to today, at this very moment? How do you think that can be done? Think about it for a moment!

Excellent now we use the .now() method and subtract the date we want to calculate. Easy!

Using strptime

This method will help us to transform dates that are given in strings to a datetime format, which is quite useful!

Let's see it in action:

As we see, we have passed two parameters to the strptime method, the first has been the string of the date, and the second the "directive" in which we want to make the conversion. To see all the available "directives", go to the following link:

Screenshot%20from%202020-11-17%2011-54-04.png

Screenshot%20from%202020-11-17%2011-54-15.png

Screenshot%20from%202020-11-17%2011-54-24.png

We already have parsed our date in the parsed_date variable, now let's start making calls to the methods it contains.

Using strftime

All right, now let's do the opposite operation, passing a datetime type as a parameter to the strftime function and converting it to a string. We do it like this:

As you can see, we pass datetime.now() as the first argument and then the directives of the formats in which we want the output. Really simple!

Time object

A time object represents a time of day (local), independent of any particular day, and subject to adjustment through a tzinfo object.

Screenshot%20from%202020-11-17%2013-14-27.png

All arguments are optional. tzinfo can be None, or an instance of a tzinfo subclass. The rest of the arguments can be integers, in the following ranges:

Screenshot%20from%202020-11-17%2013-16-12.png

If an argument is given outside these ranges, the Value-Error is raised.

All default values are 0 except tzinfo, which defaults to None. Time to play with this object!

As we can see it will give us a time object as a result. However, it has a not very "friendly" format. With the time object we can use the isoformat

We can see that there are several iso formats to display the time. We use different formats, and the default one is auto, which we can use without passing a parameter explicitly.

Screenshot%20from%202020-11-17%2013-28-24.png

timedelta object

A timedelta object represents a duration, the difference between two dates or times, which is quite useful! Let's look how it works. First we need to importa timedelta and then we need to call the different built-in functions

We've passed the parameter days = 365 to timedelta and then called two functions. One of them returns the total seconds that 365 days have.An the other one creates 10 years.

Let's make another calculations

We have now done a boolean operation, where we ask if one timedelta is the same as another. For which we get a True.

Naive & Aware methods

There are two types of date and time objects: "naive" & "aware".

An "aware" object has sufficient knowledge of the applicable algorithmic and political time settings, such as time zone and daylight savings information, to be able to position itself in relation to other "aware" objects.

An "aware" object is used to represent a specific moment in time that is not open to interpretation. Ignore Relativity

A "naïve" object does not contain enough information to place itself unambiguously in relation to other date/time objects

Whether a "ship" object represents Coordinated Universal Time (UTC), local time or the time of some other time zone depends purely on the program, just as it depends on the program whether a given number represents meters, miles or mass

The "naive" objects are easy to understand and work with, at the cost of ignoring some aspects of reality.

This finally serves us to work time zones, and time changes (depending on summer-winter) and American zones as for example EST or EDT

Supporting time zones at deeper levels of detail depends on the application.

The rules for time adjustment worldwide are more political than rational, change frequently, and there is no standard suitable for every application other than UTC

Objects of this type are immutable.

Objects of the date type are always naive.

Hope you enjoyed this reading!