Python has an in-built module named DateTime to deal with dates and times in numerous ways. In this article, we are going to see basic DateTime operations in Python.
There are six main object classes with their respective components in the datetime module mentioned below:
Now we will see the program for each of the functions under datetime module mentioned above.
We can generate date objects from the date class. A date object represents a date having a year, month, and day.
Syntax:datetime.date( year, month, day)
strftime to print day, month, and year in various formats. Here are some of them are:
- current.strftime(“%m/%d/%y”) that prints in month(Numeric)/date/year format
- current.strftime(“%b-%d-%Y”) that prints in month(abbreviation)-date-year format
- current.strftime(“%d/%m/%Y”) that prints in date/month/year format
- current.strftime(“%B %d, %Y”) that prints in month(words) date, year format
Current Day is : 23 Current Month is : 3 Current Year is : 2021 Let's print date, month and year in different-different ways format1 = 03/23/21 format2 = Mar-23-2021 format3 = 23/03/2021 format4 = March 23, 2021
A time object generated from the time class represents the local time.
Syntax: datetime.time(hour, minute, second, microsecond)
default_hour = 0 default_minute = 0 default_second = 0 default_microsecond = 0 time_1 = 10:05:25 time_2 = 10:05:25 time_3 = 10:05:25.000055
datetime.datetime() module shows the combination of a date and a time.
Syntax: datetime.datetime( year, month, day )
datetime.datetime(year, month, day, hour, minute, second, microsecond)
Current date and time using the strftime() method in different ways:
- strftime(“%d”) gives current day
- strftime(“%m”) gives current month
- strftime(“%Y”) gives current year
- strftime(“%H:%M:%S”) gives current time in an hour, minute, and second format
- strftime(“%m/%d/%Y, %H:%M:%S”) gives date and time together
2021-03-23 19:00:20.726833 print each term individually day: 23 month: 03 year: 2021 time: 19:00:20 printing date and time together date and time: 03/23/2021, 19:00:20 first_output: Mon Mar 15 14:05:22 2021 second_output: 03/15/21 third_output: 14:05:22 year = 2021 month = 3 hour = 23 minute = 55 timestamp = 1616955959.34238
It shows a duration that expresses the difference between two date, time, or datetime instances to microsecond resolution.
Here we implemented some basic functions and printed past and future days. Also, we will print some other attributes of timedelta max, min, and resolution that show maximum days and time, minimum date and time, and the smallest possible difference between non-equal timedelta objects respectively. Here we will also apply some arithmetic operations on two different dates and times.
Present Date : 2021-03-25 22:34:27.651128
Date after 10 days : 2021-04-04 22:34:27.651128
Date before 10 days : 2021-03-15 22:34:27.651128
One year before present Date : 2022-03-25 22:34:27.651128
One year before present Date : 2020-03-25 22:34:27.651128
print some other attributes of timedelta
Max : 999999999 days, 23:59:59.999999
Min : -999999999 days, 0:00:00
Total number of seconds in an year : 31536000.0
Apply some operations on timedelta function
Time after one minute : 2021-03-25 22:35:27.651128
Timedelta absolute value : 20 days, 0:00:00
Timedelta string representation : 5 days, 20:00:40.355000
Timedelta object representation : datetime.timedelta(days=5, seconds=72040, microseconds=355000)
It is an abstract base class for time zone information objects. They are used by the datetime and time classes to provide a customizable notion of time adjustment.
There are the following four methods available for tzinfo base class:
- utcoffset(self, dt): returns the offset of the datetime instance passed as an argument
- dst(self, dt): dst stands for Daylight Saving Time. dst denotes advancing the clock 1 hour in summer so that darkness falls later according to the clock. It is set to on or off. It is checked on the basis of the following elements:
(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0)
- tzname(self, dt): It returns a Python String object. It is used to find the time zone name of the datetime object passed.
- fromutc(self, dt) : This function returns the equivalent local time and takes up the date and time of the object in UTC. It is mostly used to adjust the date and time. It is called from default datetime.astimezone() implementation. The dt.tzinfo will be passed as self, dst date and time data will be returned as an equivalent local time.
Note: It raises ValueError if dt.tzinfo is not self or/and dst() is None.
Operations on normal datetime 5:30:00 0:00:00 IST 5:30:00 0:00:00 IST Opeartions on ambiguous datetime 5:30:00 0:00:00 IST 5:30:00 0:00:00 IST
Description: It is a class that implements the tzinfo abstract base class as a fixed offset from the UTC.
UTC Asia/Calcutta US/Eastern 2021-03-16 06:00:00 IST+0530 2021-03-15 20:30:00 EDT-0400 2021-03-16 12:00:00 UTC+0000 2021-03-16 05:50:00 IST+0530 2021-03-16 05:50:00 IST+0530 2021-03-16 06:10:00 IST+0530
Let’s see different Functions with description under time module :-
|time( )||Returns the time in floating point number in seconds|
|ctime( )||Returns the current date and time|
|sleep( )||Stops execution of a thread for the given duration|
|localtime( )||Returns the date and time in time.struct_time format|
|gmtime( )||Returns time.struct_time in UTC format|
|mktime( )||Returns the seconds passed since epochs are output|
|asctime( )||Returns a string representing the same|
Now we will see the program and output for each of the above-mentioned functions in the table.
1: time( ) method: The time() method returns the time as a floating-point number expressed in seconds since the epoch, in UTC.
Syntax: time.time([ ])
NOTE: It does not have any parameter
2: ctime( ) method
ctime() method converts a time expressed in seconds since the epoch to a string representing local time. The current time as returned by time() is used If secs is not provided or None. This method is equivalent to asctime(localtime(secs)). Locale information is not used by ctime() method.
Syntax: time.ctime([ sec ])
Where sec passed as an argument is the number of seconds to be converted Into string representation.
Sat Jul 10 14:02:49 2021
3: sleep( ) method
Python time method sleep() stops execution for the given number of seconds. The floating-point the number can be passed as an argument to get more precise sleep time.
Syntax: time.sleep([ sec ])
where sec passed as an argument is the number of seconds for which
the process is to be stopped.
4: localtime( ) method
localtime() method converts number of seconds to local time. If secs is not provided or None, the current time as returned by time() is used. The dst flag is set to 1 when DST applies to the given time.
Syntax: time.localtime([ sec ])
Where sec passed as an argument is the number of seconds to be converted into struct_time representation.
time.struct_time(tm_year=2021, tm_mon=3, tm_mday=30, tm_hour=8, tm_min=48, tm_sec=58, tm_wday=1, tm_yday=89, tm_isdst=0)
5: gmtime( ) method.
gmtime() method converts a time expressed in seconds since the Epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used.
Syntax: time.gmtime([ sec ])
Where sec passed as an argument is the number of seconds to be converted into structure struct_time representation.
time.struct_time(tm_year=2021, tm_mon=3, tm_mday=30, tm_hour=8, tm_min=49, tm_sec=18, tm_wday=1, tm_yday=89, tm_isdst=0)
6: mktime( ) method
It is the inverse function of localtime() method. It takes an argument as struct_time or full 9-tuple and it returns a floating-point number. If the input value is not represented as a valid time, then either OverflowError or ValueError is raised.
Where t passed as an argument is a time.struct_time object or a tuple containing 9 elements corresponding to time.struct_time object
time.mktime(t) : 1455531218.000000 asctime(localtime(secs)): Mon Feb 15 10:13:38 2016
7: asctime( ) method
Python time method asctime() converts a struct_time representing a time as returned by gmtime() or localtime() to a 24-character string of the following form: ‘Tue Mar 23 23:21:05 2021’.
Where t passed as an argument is a tuple of 9 elements or struct_time representing a time as returned by gmtime() or localtime() function.
asctime : Tue Mar 16 06:02:42 2021
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course