Facebook PageView

How to convert a date string to different format in Python.

Written by Parvatiandsons Team

I assume I have import datetime before running each of the lines of code below.

changFormet = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
print(changeFormate)

Output:-

prints "01/25/13".

Now let's call the ctime method to print the date in another format:

print('ctime:', today.ctime())

Output:

ctime: Sat Sep 15 00:00:00 2018

The ctime method uses a longer date-time format than the examples we saw before. This method is primarily used for converting Unix-time (the number of seconds since Jan. 1st, 1970) to a string format.

And here is how we can display the year, the month, and the day using the date class:

print('Year:', today.year)
print('Month:', today.month)
print('Day :', today.day)

Output:

Year: 2018
Month: 9
Day : 15

Converting Dates to Strings with strftime

To achieve this, we will be using the strftime method. This method helps us convert date objects into readable strings.

This method can also be used on a datetime object directly, as shown in the following example:

import datetime

x = datetime.datetime(2018, 9, 15)

print(x.strftime("%b %d %Y %H:%M:%S"))

Output:

Sep 15 2018 00:00:00

We have used the following character strings to format the date:

  • %b: Returns the first three characters of the month name. In our example, it returned "Sep"
  • %d: Returns day of the month, from 1 to 31. In our example, it returned "15".
  • %Y: Returns the year in four-digit format. In our example, it returned "2018".
  • %H: Returns the hour. In our example, it returned "00".
  • %M: Returns the minute, from 00 to 59. In our example, it returned "00".
  • %S: Returns the second, from 00 to 59. In our example, it returned "00".
  •     How to add onchange event in django-python
  • How to convert to 12 hour clock