Data Science and Machine Learning Internship ...
- 22k Enrolled Learners
- Weekend/Weekday
- Live Class
Time is undoubtedly the most critical factor in every aspect of life. Therefore, it becomes very essential to record and track this component. In Python, date and time can be tracked through its built-in libraries. This article on Date and time in Python will help you understand how to find and modify the dates and time using the time and datetime modules.
Python provides time and datetime module that help you to easily fetch and modify date and time. Let’s take a look at each of these in detail.
This module consists of all the time-related functions that are required to perform various operations using time. It also allows you to access several types of clocks required for various purposes.
Take a look at the following table which describes some of the important built-in functions of the time module.
Function | Description |
time() | Returns the number of seconds that have passed since epoch |
ctime() | Returns the current date and time by taking elapsed seconds as its parameter |
sleep() | Stops execution of a thread for the given duration |
time.struct_time Class | Functions either take this class as an argument or return it as output |
localtime() | Takes seconds passed since epoch as a parameter and returns the date and time in time.struct_time format |
gmtime() | Similar to localtime(), returns time.struct_time in UTC format |
mktime() | The inverse of localtime(). Takes a tuple containing 9 parameters and returns the seconds passed since epoch pas output |
asctime() | Takes a tuple containing 9 parameters and returns a string representing the same |
strftime() | Takes a tuple containing 9 parameters and returns a string representing the same depending on the format code used |
strptime() | Parses a string and returns it in time.struct_time format |
Before moving on to explain each of the functions with examples, take a look at all the legal format codes:
Code | Description | Example |
%a | Weekday (short version) | Mon |
%A | Weekday (full version) | Monday |
%b | Month (short version) | Aug |
%B | Month (full version) | August |
%c | Local date and time version | Tue Aug 23 1:31:40 2019 |
%d | Depicts the day of the month (01-31) | 07 |
%f | Microseconds | 000000-999999 |
%H | Hour (00-23) | 15 |
%I | Hour (00-11) | 3 |
%j | Day of the year | 235 |
%m | Month Number (01-12) | 07 |
%M | Minutes (00-59) | 45 |
%p | AM / PM | AM |
%S | Seconds (00-59) | 57 |
%U | Week number of the year starting from Sunday (00-53) | 34 |
%w | Weekday number of the week | Monday (1) |
%W | Week number of the year starting from Monday (00-53) | 34 |
%x | Local date | 06/07/19 |
%X | Local time | 12:30:45 |
%y | Year (short version) | 19 |
%Y | Year (full version) | 2019 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%% | % Character | % |
The struct_time class has the following attributes:
Attribute | Value |
tm_year | 0000, .., 2019, …, 9999 |
tm_mon | 1-12 |
tm_mday | 1-31 |
tm_hour | 0-23 |
tm_min | 0-59 |
tm_sec | 0-61 |
tm_wday | 0-6 (Monday is 0) |
tm_yday | 1-366 |
tm_isdst | 0, 1, -1 (daylight savings time, -1 when unknown) |
Now let us take some examples to implement the time module.
Using the built-in functions and the format codes described in the tables above, you can easily fetch the date and time in Python. Please note that just like all modules, the time module also needs to be imported before making use of any built-in function.
EXAMPLE:
import time #time a=time.time() #total seconds since epoch print("Seconds since epoch :",a,end='n----------n') #ctime print("Current date and time:") print(time.ctime(a),end='n----------n') #sleep time.sleep(1) #execution will be delayed by one second #localtime print("Local time :") print(time.localtime(a),end='n----------n') #gmtime print("Local time in UTC format :") print(time.gmtime(a),end='n-----------n') #mktime b=(2019,8,6,10,40,34,1,218,0) print("Current Time in seconds :") print( time.mktime(b),end='n----------n') #asctime print("Current Time in local format :") print( time.asctime(b),end='n----------n') #strftime c = time.localtime() # get struct_time d = time.strftime("%m/%d/%Y, %H:%M:%S", c) print("String representing date and time:") print(d,end='n----------n') #strptime print("time.strptime parses string and returns it in struct_time format :n") e = "06 AUGUST, 2019" f = time.strptime(e, "%d %B, %Y") print(f)
OUTPUT:
Seconds since epoch : 1565070251.7134922
———-
Current date and time:
Tue Aug 6 11:14:11 2019
———-
Local time :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=11, tm_min=14, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———-
Local time in UTC format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=5, tm_min=44, tm_sec=11, tm_wday=1, tm_yday=218, tm_isdst=0)
———–
Current Time in seconds :
1565068234.0
———-
Current Time in local format :
Tue Aug 6 10:40:34 2019
———-
String representing date and time:
08/06/2019, 11:14:12
———-
time.strptime parses string and returns it in struct_time format :
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=218, tm_isdst=-1)
Similar to the time module, the datetime module also consists of all the required methods that are essential for working with the date and time.
The following table describes some of the important functions present within this module:
Function | Description |
datetime() | Datetime constructor |
datetime.today() | Returns current local date and time |
datetime.now() | Returns current local date and time |
date() | Takes year, month and day as parameter and creates the corresponding date |
time() | Takes hour, min, sec, microseconds and tzinfo as parameter and creates the corresponding date |
date.fromtimestamp() | Converts seconds to return the corresponding date and time |
timedelta() | It is the difference between different dates or times (Duration) |
Now, let us try to implement these functions to find the date and time in Python using the datetime module.
EXAMPLE:
import datetime #datetime constructor print("Datetime constructor:n") print(datetime.datetime(2019,5,3,8,45,30,234),end='n----------n') #today print("The current date and time using today :n") print(datetime.datetime.today(),end='n----------n') #now print("The current date and time using today :n") print(datetime.datetime.now(),end='n----------n') #date print("Setting date :n") print(datetime.date(2019,11,7),end='n----------n') #time print("Setting time :n") print(datetime.time(6,30,23),end='n----------n') #date.fromtimestamp print("Converting seconds to date and time:n") print(datetime.date.fromtimestamp(23456789),end='n----------n') #timedelta b1=datetime.timedelta(days=30, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8) b2=datetime.timedelta(days=3, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=4, weeks=8) b3=b2-b1 print(type(b3)) print("The resultant duration = ",b3,end='n----------n') #attributes a=datetime.datetime.now() #1 print(a) print("The year is :",a.year) print("Hours :",a.hour)
OUTPUT:
Datetime constructor:
2019-05-03 08:45:30.000234
———-
The current date and time using today :
2019-08-06 13:09:56.651691
———-
The current date and time using today :
2019-08-06 13:09:56.651691
———-
Setting date :
2019-11-07
———-
Setting time :
06:30:23
———-
Converting seconds to date and time:
1970-09-29
———-
<class ‘datetime.timedelta’>
The resultant duration = -27 days, 0:00:00
———-
2019-08-06 13:09:56.653694
The year is : 2019
Hours : 13
This brings us to the end of this article on “Date and time in Python”. I hope you have understood everything clearly.
Got a question for us? Please mention it in the comments section of this “Generators in Python” blog and we will get back to you as soon as possible.
To get in-depth knowledge on Python along with its various applications, you can enroll for live Python Certification Training with 24/7 support and lifetime access.
Course Name | Date | Details |
---|---|---|
Data Science with Python Certification Course | Class Starts on 19th October,2024 19th October SAT&SUN (Weekend Batch) | View Details |
Data Science with Python Certification Course | Class Starts on 14th December,2024 14th December SAT&SUN (Weekend Batch) | View Details |
edureka.co