python时间 time和datetime总结
一、Time模块
(1)time.time()输出当前时间戳
# -*- coding: UTF-8 -*- import time; # 引入time模块 ticks = time.time() print "当前时间戳为:", ticks 输出 当前时间戳为: 1459994552.51
(2)获取当前时间,时间元组的形式localtime()
localtime = time.localtime(time.time()) print "本地时间为 :", localtime 输出结果: 本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
(3)最简单的获取可读的时间形式asctime():
localtime = time.asctime( time.localtime(time.time()) ) print "本地时间为 :", localtime 输出结果: 本地时间为 : Thu Apr 7 10:05:21 2016
(4)格式化日期
time.strftime(format[, t]),如果t未指定默认传入,默认time.localtime()
# 格式化成2016-03-20 11:45:39形式 print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #或者直接time.strftime("%Y-%m-%d %H:%M:%S")
# 格式化成Sat Mar 28 22:24:24 2016形式 print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # 将格式字符串转换为时间戳 a = "Sat Mar 28 22:24:24 2016" print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
输出结果
2016-04-07 10:25:09 Thu Apr 07 10:25:09 2016 1459175064.0
小结:
time模块中时间表现的格式主要有3种:
1. timestamp 时间戳
2. tuple或者struct_time 时间元组,共有九个元素组
3. formattime格式化字符串
(5)time.sleep(60) 推迟调用线程的运行,60s
二、datetime模块
(1)获取当前时间和日期
import datetime
print(datetime.datetime.today())
print(datetime.datetime.now())
2018-08-14 22:24:23.022380
2018-08-14 22:24:23.022380
(2)获取指定日期
>>> from datetime import datetime >>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime >>> print(dt) 2015-04-19 12:20:00
(3)datetime转换为timestamp
>>> from datetime import datetime >>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime >>> dt.timestamp() # 把datetime转换为timestamp 1429417200.0
(4)timestamp转换为datetime
>>> from datetime import datetime >>> t = 1429417200.0 >>> print(datetime.fromtimestamp(t)) 2015-04-19 12:20:00
(5)str转换为datetime
>>> from datetime import datetime >>> cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') >>> print(cday) 2015-06-01 18:19:59
(6)datetime转换为str
>>> from datetime import datetime >>> now = datetime.now() >>> print(now.strftime('%a, %b %d %H:%M')) Mon, May 05 16:28
(7)datetime加减
加减可以直接用+
和-
运算符,不过需要导入timedelta
这个类:
>>> from datetime import datetime, timedelta >>> now = datetime.now() >>> now datetime.datetime(2015, 5, 18, 16, 57, 3, 540997) >>> now + timedelta(hours=10) datetime.datetime(2015, 5, 19, 2, 57, 3, 540997) >>> now - timedelta(days=1) datetime.datetime(2015, 5, 17, 16, 57, 3, 540997) >>> now + timedelta(days=2, hours=12) datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
参考: