Time is an important thing in many programming projects. Many software and applications need to keep track of the current time wherever you are in the world and it gets very messy when we include our way to keep track of the time. So it becomes quite important to have something to deal with it.
To deal with time, Python has a very developed module for it called the datetime module, it contains several classes for the manipulation of dates and time in Python. This module has two types of time and date objects, aware and naive. So, what is the difference between the two? Let us have a look
This type of object is intelligent enough to know about the different algorithmic and political adjustments in the time.
For example, in some countries, clocks are advanced during the summertime so that it gets dark after some time each day, this is known as daylight saving time. An aware object is intelligent enough to adjust itself relative to other aware objects.
An object of this type in the Python datetime module does not have enough information to use other date and time objects to locate itself.
These types of objects are easier to work with than the aware objects but you will have to ignore the real-world complexities like daylight saving time complexity.
datetime Main Classes
- Naive: It assumes that each day has exactly 24 hours which means that it does not consider the slowing rotation speed of Earth and other complexities. It is also a naive object.
Attributes: hour, minute, second, and microsecond.
- date: This is an ideal naive date, that is only used to manipulate dates.
Attributes: month, day, and year.
- datetime: It combines both date and time as the name suggests. This is an aware time object.
Attributes: month, day, year, hour, minute, second, microsecond, and tzinfo.
- tzinfo: It is used to get the time zone information. This makes the time customizable according to different political and geographical complexities.
Attributes: No attributes
- timdelta function: It provides a duration that expresses between two datetime objects like date, time, or datetime.
Now that we know different classes in Python’s datetime module and what they do, let us see how to use each class to get information about date and time.
An object instantiated from the time class represents the local time independent of the day.
Get hour, minute, second, and microsecond
An object instantiated from the time class represents the local time independent of the day.
datetime module works on integers mostly. So above, we created the integer values given by the Python datetime module to strings.
If you do not want to pass the value of either of the parameters then the default value i.e. 0 will be used to provide the results.
You do not have to use the print statement as we used in the example above, the time object provides a default formatting. Let us create different objects to see default values and the default formatting.
Example - Input
We did not pass any arguments in the beginning, and Python returned default values for all of the parameters. Then, we started providing values one by one for each argument, so, Python passed default values only for the values that did not have any value.
This class in the datetime module of Python provides dates information. The objects can be instantiated from the date class similar to the time class we used above.
The correct argument position is year, month, and day. If you are from a place where this date format is not used, do not get confused, you can specify the name of the parameter to pass it as an argument in Python to get the date format you are familiar with (There is a better way to deal with this problem that we shall discuss later in this article).
By using the function today() method in date class, you can get the date of the current day. Let us see how:
You can also print specific values for year, month or day using the dot separator like this:
The current weekday number can also be obtained with the help of the today.weekday() function in Python. For the function, the week starts from Monday and ends on Sunday. It uses values from 0-6 (Total 7) to represent each weekday.
To make it more realistic, we can add 1 to it, so that Monday becomes equal to 1 and Sunday becomes equal to 7.
This function only returns the weekday number and not the actual name of the weekday, so let us write a simple program that will return the weekday name using this function.
You can get a custom date; you can do it by putting all of the values of date in the date class in the datetime module.
If you pass wrong values for the parameters then the Python compiler will show a value error. For example, if you pass the value of the month as 13, or of the day as 32, Python will not be able to compile it.
This “feature” is useful in itself and can help you to avoid date and time mistakes in your program.
Python Timestamp to datetime
A timestamp is a piece of coded information to identify the occurrence of an event at a particular time. Almost every computer is counting seconds from 1 January 1970 GMT (Greenwich Mean Time).
A UNIX timestamp is an exact amount of seconds that have passed since 1 January 1970, this timestamp can be transformed to get a date using the Python datetime’s timestamp() method.
Python’s module datetime contains a similarly named class called the datetime class. This class contains information about both date and time.
datetime class also provides timezone aware objects which means that this class is able to return the current time according to your timezone.
First, let us use this class to get the current date and time. The function now() in the Python datetime class is used to get the current information of date and time.
Current date and time
You can also pass custom values for time and date. You will have to pass every value of date in the order – year, month, day, and every value of day in the order – hour, minute, second, microsecond.
Printing Individual Values of date and time
Separate values can be printed from the datetime class for date and time. Let us have a look at an example –
Separate values can be printed from the datetime class for date and time. Let us have a look at an example
Python Datetime to Timestamp
You have learnt how to convert a timestamp into datetime, however, the opposite can also be done i.e., datetime can also be converted into a timestamp using the timestamp() function from the object instantized from the datetime.now() in the datetime class from the Python datetime module.
This is also called converting Python datetime to epoch. Epoch means a particular event in time.
You can compare dates in Python like you compare numbers. The datetime class can be used for this purpose too.
To compare dates, you will have to use the comparison operators available in Python.
We used the now() method in the datetime class, but it does not contain any information about timezones, therefore to get time and dates according to your timezone, you will have to use the tzinfo class which is an abstract class.
What is an abstract class?
A class that cannot be instantiated directly is called an abstract class. A substantial class in Python like datetime can use time zones and it would have to derive tzinfo and use the functions that are provided by tzinfo.
Functions used by this class are:
- utcoffset(self, dt)
- tzname(self, dt)
- dst(self, dt)
- fromutc(self, dt)
You can get more information about the class on the Python Documentation.
This function is usually used to calculate the difference between two dates. However, this can also be used to manipulate dates in Python and it provides one of the easier ways to do it.
The object of this function is used to represent the difference between two dates and times.
First, let us see how to calculate differences between two dates or times. You will need the datetime or the date class to use this object.
For our example, we will use the datetime function.
As you can see that our output difference of the dates is of type timedelta.
The function in the datetime module, however, can be used to manipulate dates and time. You can calculate what would be the date or time after a particular time.
Arguments that are used by timedelta() are: timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
Let us have an example: –
Python datetime strftime
The date and time formats are different everywhere in the world, for example, in the UK the format dd-mm-yyyy is used, whereas mm-dd-yyyy is common in the USA.
To deal with it, Python provides the strftime() method, this is a method in the datetime class, let us see how you can use it to format your date and time.
- We used the strftime() function to format the date into the dd/mm/yyyy format which is used most commonly in the world. It is a string, so you can use any format you want. The % (percentage) operator is used to access the specific values of each parameter.
- The time is printed in the hour:minute:second format, and similar to the date object, you can use any format.
- We print both the time and date value with the help of strftime() method;
Remember that we wrote a code to get the weekday name from the date class? Well, if we use the strftime() function, we will not have to write the whole code, the weekday can be obtained simply like this:
|%w||For the weekday number, from 0-6, where 0 is Sunday|
|%a||For the short weekday name|
|%A||For the full weekday name|
|%d||Day number in the month|
|%B||Long name of the month|
|%b||Short name of the month|
|%m||Month number in a year|
|%y||Short form of the year, e.g., returns 2018 as 18|
|%Y||Long form of the year, e.g., returns 2018 as 2018|
|%H||Hour in the 24Hr format|
|%I||Hour in the 12Hr format|
|%p||For the representation of AM and PM|
|%M||Minutes in an hour|
|%S||Seconds in a minute|
|%f||Microseconds in a second|
|%Z||Gets the timezone (Default is UTC)|
|%z||Gives the value of the UTC offset|
|%j||Day number in the year|
|%U||Week number in the year (Sunday is the first day in the week)|
|%W||Week number in the year (Monday is the first day in the week)|
|%c||Local representation of time and date|
|%X||Local representation of time|
|%x||Local representation of date|
Python datetime strptime
The method strptime() from the datetime class can create a datetime object from a string. The string must represent time and date. Let us know how to obtain a date from a string in Python. Consider this as an example:
To get better at understanding anything in programming, you have to practice and the same applies for the datetime module, so keep practicing and learning!