Python : Date & Time
Getting the current time with python
datetime
from datetime import datetime
We are importing the datetime class from the datetime module. Now that we have the datetime module here, we can get information about the current time, date……
from datetime import datetime
now = datetime.now()
datetime:accessing that class
give the current date and time according to this comupter
print(now.date())
输出结果
2018-02-15
输入
print(now.year)
print(now.hour)
输出(晚上22:46做的)
2018
22
print out the whole current time which will have the hout, minute and second with now.time() as a method.
输入
print(now.time())
打印
22:48:16.290149
Formatting dates and times in python with datetime
we can actually control the format of our dates and times with strings. We’ll use something called “shift time” with he shift time method. It takes one string, and what’s in the string determines how the contents of the “now” variable are displayed. First, we’ll control how the day of a given week or month is displayed. With %a we can have an abbreviated day of the week with just Mon, Tues, Wed displayed. With %A, we can show the full name of the day of the week.
And we can also display the day as the day of the month with %d. So if it was going to be the tenth day of the month, %d would translate to ten.
%a —> the abbreviated day of the week,
%A —–> the full day of the week
%d —–> the numbered day of the week.
print(now.strftime("%a %A %d"))
output
Thu Thursday 15
%b —-> the abbreviated name of the month
%B —-> the full name of the month
%m ——> the number of the month out of the year
output
Feb February 02
In addition to days and months, we can also format time.
We will have
%H ——-> to display the hours
%M———> to show the minutes
%S————> to show the seconds
and %p ——–> for AM or PM
Lastly, we’ll format years. If we only want two numbers for the year to be displayed, we’ll use %y. If we want four numbers, we’ll use %Y. Trying this in the code, we’ll go print now dot shift time, and then %y, %Y and we’ll get the two different formats for the year, which are 16 and 2016.