Remove seconds from the datetime in Python
In this tutorial, you will learn about how to remove seconds from the datetime in Python. Python has a module datetime that provides classes for manipulating dates and times in a complex and simple way.
Here we are going to use some predefined class and predefined method to remove seconds from the datetime module in Python.
- datetime() class
- strftime() method
As datetime is a module we have to import it. Where datetime() is the class and strftime() is the method of this module.
#importing datetime module import datetime
In the above python program, we have imported the datetime module using the import function.
Datetime() class
It is the combination of date and time also with the addition of some attributes like the year, month, timezone information, etc.
Now let’s see an example to print the current date and time using the datetime module->
from datetime import datetime print("Current date and time:",datetime.now())
Output:
Current date and time: 2020-01-16 16:50:28.303207
In the above python program, we have imported the datetime module and printed the current date and time.
strftime() method
The strftime() method is defined under the classes of time, date, datetime modules. This method creates a string using provided arguments.
Now let’s see an example:
from datetime import datetime cdate=datetime.now() print("Year:",cdate.strftime("%Y")) print("Month:",cdate.strftime("%m")) print("Date:",cdate.strftime("%d"))
Output:
Year: 2020 Month: 01 Date: 16
In the above python program, using the datetime module and strftime() method we have modified the date and time into the required string. Here %Y, %m, %d are format codes for year, month, date. So the first print statement print the year and the second one prints the month and finally the third one prints the date.
Program to remove the seconds from the datetime in Python
from datetime import datetime print("Present date and time:",datetime.now()) print("Datetime with out seconds",datetime.now().strftime("%Y-%m-%d, %H:%M"))
Output:
Present date and time: 2020-01-16 17:10:29.795763 Datetime without seconds 2020-01-16, 17:10
In the above program, using the datetime module we have imported and printed the present date and time in the first step. Finally, in the last step of our script, we have printed the modified date and time by removing the seconds from the present date and time.
Thanks for this information
It was much useful for me