Date and time is an important part of application development. We generally need to set, get, and change some data time information to our records. In this tutorial, we will examine the python date time now functions and use cases with examples. For more information about Python date-time functions can be get from the following tutorial.
Import datetime Module To Use datetime Functions
In order to use datetime functionalities, we should import the module named
datetime . We can import
datetime module like below.
Print Now with datetime.now() Function
datetime module we can use provided class and functions. The simplest and most basic way to get the current date and time is using datetime.now() function. This resides inside datetime module which means we should use the following code in order to get the current date and time.
We can see that every time we execute the now() function it returns different date time information where generally the second changes. The now() function returns date time infomation in
datetime format with
(YYYY, M, D, H,M,S) format.
Convert Now (Current Time) To String
now() function returned data will be a datetime object. But in some situations, we may need to convert date-time into a string to use string variable or print to the console. We can use str() functions that will convert current date time to string.
Print Now (Current Time) According To GM (Greenewitch Meantime)
We can use
gmtime() function which will print current GM time. GM time is the current time in Greenwich where the world time starts and ends. We should
import time module in order to use
import time time.gmtime()
Print Specific Part Of Now (Current Time)
In this part, we will print an only specific part of the current time. We will use specifiers in order to print only the required part of the time. We assume we have got the current time into a variable named
now like below.
now = datetime.datetime.now()
Print Current Second
We can print current second like below.
Print Current Minute
We can print current minute like below.
Print Current Hour
We can print current hour like below.
Print Current Day of Month
We can print current day of month like below.
Print Current Month
We can print current month like below.
Print Current Year
We can print current year like below.