Python Date and Time

As we generally give utmost importance to our time, so does python. It has something called ‘time’ which is inbuilt but though the importance of time remains same in all spheres, yet the purpose served is different.

The magic basket as you remember has this most important element in it, which is almost used by every coder in most dynamic, static and graphic oriented codes. Let’s check out what is so much interesting which makes ‘python time’ different from ‘ours’

Technically Python contains a module named datetime to get the access with dates and times. Let’s have a fair idea of what this is actually about, by a simple basic code:

Code:

import datetime
    techistime = datetime.datetime(2020,8,25)
    #this will display the date
    print(techistime)

Output:

2020-08-25 00:00:00    >>> 

Further classifying the date and time classes into the following 6 main classes –

1. Date: It runs the code in such a way that it displays the date.

2. Time: Dependent expression of the date.

3. Datetime: Combinatorial of both date and time as a single unit.

4. Timedelta: Expression for representing date and time together.

5. Tzinfo: Time zonal expression for date.

6. Timezone: Class of amendment for the date functions.

Date and time-related Modules in Python

Date and time play a very crucial role in any programming, if not assigned the true value these two functions work according to the binary value provided by the CPU.

Date and time function together helps the coder achieve the internal logistics of the executable code manually from the code itself. There are various types of modules in date and time, which are very extensible and helpful for any code.

Index  Format type values
0 Year (4 digits)  xxxx
1 Month   0-12
2 Second   0 to 61 (60/61 are leap seconds)
3 Day of Week  0 to 6 (Monday to Sunday)
4 Day of Year  1 to 366 (Julian day)
5 dst  -1,0,1
6 Hour 0 to 23
7 minute 0 to 59

Datetime in Python

This gives an insight to the delta-related objects in the code. In timedelta objects, the user is asked to input the time-related data, and then the code interprets the data in runtime and then displays the output.

Time delta provides the difference between the two-time units as well, it allows the user to enter two values or takes the CPU value by default.

Handling timezone in Python: This is a simple way to manipulate the time according to the user. Handling the timezone literally means manipulating the time according to the need of the coder, and this can be simply done by changing the default time to the set time module.

Code:

from datetime import datetime
now= datetime.now()
#it will display the current time
thisistech = now.strftime("%H:%M:%S")
print("time:", thisistech)

Output:

time: 19:44:57>>>

Python format datetime

The way date and time is represented can be different in different places, organizations. It is generally used by the coders so as to keep a check on the user as well.

The datetime module has a class named dateclass which can contain information from both date and time objects. This also print years, months, hours, minute and timestamp

Datetime.date Class : This helps the coder in searching the current time in the code. We can also create date objects from a timestamp attribute. A timestamp is the number of seconds between a particular date and January 1, 1970 at UTC.

One can convert a timestamp to date using the fromtimestamp() method. Different functions in date class() are as follow:

Function  Description 
fromtimestamp(timestamp) Return local date
fromordinal(ordinal) Return the date corresponding to the proleptic Gregorian ordinal
fromisoformat(date_string) Return a date corresponding to a date_string given in the format YYYY-MM-DD:
fromisocalendar(year, week, day) Return a date corresponding to the calendar date specified by year, week and day.

Example

from datetime import date
techistime= date.fromtimestamp(1326244364)
#this will display the date 
print("the date today is", techistime)

Output

the date today is 2012-01-11

>> 

Python Timedelta

It is basically an object that represents the duration of the code. Is mainly used to calculate the duration between any two dates or any two times. It is used for retrieving the object case with some delta date or time.

Time delta as in mathematics represent the difference between the small rate occuring events, it also allows the user to calculate the period of time. Time deta also provides the coder to code in such a way that the default code object gets replaced by the user entered object in the code.

For Example

from datetime import timedelta
#t1_ = timedelta(seconds = 45)
#t2= timedelta(seconds = 34)
t3 = 90
print("t3_ =", 90)

Output

t3_ = 90>>> 

Difference between two dates and times: This can be done by simply comparing two different delta objects. And this performs a while loop inside the code. The usage of for loop in this method is strictly prohibited, as the recursive allowance for different dates or times may damage the code to much extent.

Example

from datetime import datetime, date
t1 = date(year = 2020, month = 7, day = 12)
t2 = date(year = 2021, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
t4 = datetime(year = 2020, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2021, month = 12, day = 23, hour = 5, minute = 55, second = 13)
t6 = t4 - t5
print("t6 =", t6)

print("type of t3 =", type(t3)) 
print("type of t6 =", type(t6)) 

Output

t3 = -529 days, 0:00:00t6 = -529 days, 1:14:20

type of t3 = <class ‘datetime.timedelta’>

type of t6 = <class ‘datetime.timedelta’>

>>> 

Difference between two timedelta objects: This provides the difference between any two delta objects if instructed by the coder. The usage of time delta object can also be done on one object only, taking the other as a default value from the CPU. Subsequently, the predefined values give more accuracy in the code.

Example

#t1 = week = 2, day = 5, hour = 1, seconds = 38
#t2 = day = 4, hours = 11, minute = 4, second = 54
t3 = 14
print("t3 =", t3)

Output

t3 = 14>>> 

Python Tzinfo class

This class signifies that the abstract value of a code can not be given as input directly. It proceeds as an individual value in the code, with tzinfo as a class function. From the major time module, it extracts the random values and calculates them as the input in the run time.

The UTC methods to perform this class can be majorly done by the source code only. The tzinfo provides the coder a chance to work with the time module in such a way that his own codes may get set to the default, and the CPU time may not be considered in any further code.

Example

from datetime import timedelta
t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
print("t3 =", abs(t3))

Output

t3 = -1 day, 23:59:39t3 = 0:00:21

Python Timezone class

It is a subcategory of tzinfo which acts as an interpreter sheet between any two integral values of code. It operates on one value at one time. Time zone class also provides a coder the integral value of any calculative code as an option to convert the same in time as well.

This class is although not frequently used by the coder because of the already present datetime class(). Yet it is important for the coder to check the date-time calculation for accuracy in this class as well.

Conclusion

Having read and applied all the codes in the article, a coder gets a fair idea of what python time actually is like. It is as important as the coder’s time in any dynamic code.

Time is fun, and complicated at the same time. To get its best is practicing more and more codes, and remembering the usage and syntax too. Happy pythonning!