Python Django convert date time to string

In this Python Django tutorial, we are going to discuss how we can convert date, time, and datetime objects to strings. We will see this through examples.

How to convert a date-time object into a string in python?

To change over date time into a string we will utilize the strftime() technique which restores us to a datetime object as a string. We will see the accompanying code to perceive the way this functions. We will likewise import the datetime class from datetime module. See the example below.

Write this code in the views.py file.

INPUT:

from datetime import datetime

now = datetime.now() 

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)	

Now let’s go through the details of the directives we have used in this method.

  • %Y – it formats code to year as a decimal number.
  • %m – it formats month as a decimal number added to that.
  • %d – it formats the day of the month with zero-padded decimal. (01,02)
  • %H – it converts the hour block of 24 hours as a zero-padded decimal number.
  • %M – it converts the Minute as a zero-padded decimal number.
  • %S – it converts the Seconds as a zero-padded decimal number.

OUTPUT:

year: 2023
month: 03
day: 24
time: 13:08:06
date and time: 03/24/2023, 13:08:06

We have got the current time and date in the string format.

Output:

Python django convert date time to string
Python django convert date time to string

Conclusion

In this Python Django tutorial, we came to know about Datetime class of Python and we successfully converted a date time format into a string with the help of the strftime() function. We also came to know about the derivatives used and their functionalities.

READ:  How to add dropdown navbar in Django

You may also like to read the following articles: