How to Convert Date and Time to String in Python

In different kind of analytics and programming lifecycle we need to format date and time object to String. By using the strftime() function, we can format date and time object to String in Python. In this tutorial I’ll show you by giving some Python examples.


import datetime
current_datetime=datetime.datetime.now()
print("current date and time:",current_datetime)
str_date = current_datetime.strftime("%d-%b-%Y")
print("current date:",str_date)
str_date_time = current_datetime.strftime("%d-%b-%Y %I:%M:%S %p")
print("current date and time with AM/PM:",str_date_time)
print("The Current day is: ",current_datetime.strftime("%d"))
print("The Current week is: ",current_datetime.strftime("%W"))
print("The Current month is: ",current_datetime.strftime("%B"))
print(" The Current year is: ",current_datetime.strftime("%Y"))

Output:
current date and time: 2022-12-29 23:22:31.606069
current date: 29-Dec-2022
current date and time with AM/PM: 29-Dec-2022 11:22:31 PM
The Current day is: 29
The Current we ek is: 52
The Current month is: December
The Current year is: 2022

 

I have an another article How to format Date Time Data Object in Python, from where you can learn about different formatting on date & time in Python and you can also bookmark it for your working reference.

In this tutorial, I tried to brief how to convert Date and Time Object to String in Python . Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.

Add a Comment