python日期操作

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值