In this article, we are going to learn how we can convert data time object to string. We will make use of the datetime module of Python to get the current date and time. Once we
have it then we will convert it to a string.
Environment and Requirement: –
Python Interpreter
datetime Module
Convert Date time to String in Python
from datetime import datetime
my_datetime = datetime.today()
format='%d/%m/%y %H:%M:%S:%MS'
my_datetime = my_datetime.strftime(format)
print(my_datetime)
Output:
28/12/22 07:57:43:57S
Code Explanation:-
- Import datetime from datetime module.
- Used “my_datetime” as an Object of datetime Class in which datetime.today()
is stored and it will return current local date. - Get input from user in specified format.
- my_datetime.strftime() is stored in “my_datetime” which will return the string representation of date.
- Finally, used print function to get output of code.