Python获取当前时间

time模块(low level)

语法:

1
2
import time
time.strftime(format)

获取当前时间:

1
2
3
4
5
6
import time
## 24 hour format
time.strftime("%H:%M:%S") # 输出 18:58:17
## 12 hour format
time.strftime("%I:%M:%S") # 输出 06:58:17
##

获取当前日期:

1
2
3
import time
## yyyy-mm-dd format
time.strftime("%Y-%m-%d") # 输出 2017-06-23

datetime模块(high level Object-oriented interface to dates and times)

语法:

1
2
3
import datetime
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # 输出 2017-06-23 18:58:17

获取年/月/日/时/分/秒

1
2
3
4
5
6
7
8
9
10
import datetime
now = datetime.datetime.now() # 当前datetime,输出 datetime.datetime(2017, 6, 23, 19, 13, 43, 555000)
now.year # 年
now.month # 月
now.day # 日
now.hour # 时
now.minute # 分
now.second # 秒
now.isoformat() # Date and time in ISO format,输出 2017-06-23T19:16:21.835000

strftime()参数含义对照表:strftime() format codes

大师兄 wechat
欢迎关注我的微信公众号:Python大师兄