Time is a precious thing in every one’s life. In python, there is a module called “datetime”. It has lot of functions. Generally, this module is used to get the date and time.
For using
this module, the user should import the module by
import datetime
Next, create
a variable for datetime module by,
dt =
datetime.datetime.now()
where,
dt is the
variable. datetime is the module and another datetime is the class. Now() is
the function to get the current time and date and assigned it to variable dt.
To print
the date and time
print(dt)
While
executing this code, user get the following output.
Here, first part is date. Next part is time in hours, minutes, seconds and micro seconds.
A simple
program to display messages based on the time:
import
datetime
dt =
datetime.datetime.now()
if dt.hour
< 12 :
print("Hi, Good morning. It's " +
str(dt.hour) +"'O clock")
elif 12
< dt.hour < 16 :
print ("Hi, Good afternoon.It's "
+ str(dt.hour) +"'O clock"")
elif 16
< dt.hour < 18 :
print("Hi, Good Evening.It's " +
str(dt.hour) +"'O clock"")
else :
print("Hi, Good night.It's " +
str(dt.hour) +"'O clock"")
It displays
the following output.
Date – It
displays date.
Time - It
displays time
Timedelta –
It gives the difference between two dates or time
Timezone – It
displays time zone from coordinated universal time.
Tzinfo – it
involves with time zone objects.
These the basic usage of datetime module in python.
No comments:
Post a Comment