Date time formet change.
I assume I have
import datetimebefore running each of the lines of code below.
changFormet = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y') print(changeFormate)
Now let's call the
ctimemethod to print the date in another format:
ctime: Sat Sep 15 00:00:00 2018
ctimemethod 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
print('Year:', today.year) print('Month:', today.month) print('Day :', today.day)
Year: 2018 Month: 9 Day : 15
Converting Dates to Strings with strftime
To achieve this, we will be using the
strftimemethod. This method helps us convert date objects into readable strings.
This method can also be used on a
datetimeobject directly, as shown in the following example:
import datetime x = datetime.datetime(2018, 9, 15) print(x.strftime("%b %d %Y %H:%M:%S"))
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".