时间的表示类型
py中可能涉及的time有四种类型
- time string
- datetime tuple(datetime obj)
- time tuple(time obj)
- timestamp
时区
time string
string 是最简单的表示时间的方式,如以下代码生成的即为 string:
>>> time.ctime()
'Mon Dec 17 21:02:55 2012'
或者更简单的生成一个字符串:time_string = "2000-01-02 03:04:05"
datetime tuple(datetime obj)
datetime tuple 是 datetime.datetime 对象类型
>>> datetime.now()
datetime.datetime(2012, 12, 17, 21, 3, 44, 139715)
time tuple(time obj)
time tuple 是 time.struct_time 对象类型
time.struct_time(tm_year=2008, tm_mon=11, tm_mday=10, tm_hour=17, tm_min=53, tm_sec=59, tm_wday=0, tm_yday=315, tm_isdst=-1)
timestamp
时间戳类型: 自 1970年1月1日(00:00:00 GMT) 以来的秒数
>>> time.time()
1355749338.05917
类型之间的转换
string 转换为其它
初始化: date_str = "2008-11-10 17:53:59"
string —> datetime obj
导入:
import datetime
datetime.datetime.strptime(string, format)
>>> dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> dt_obj
datetime.datetime(2008, 11, 10, 17, 53, 59)
string —> time obj
导入:
import time
time.strptime(string, format)
#time模块有类似datetime中的strptime()函数
>>> date_str = "2008-11-10 17:53:59"
>>> t_obj = time.strptime(date_str, "%Y-%m-%d %H:%M:%S")
>>> t_obj
time.struct_time(tm_year=2008, tm_mon=11, tm_mday=10, tm_hour=17, tm_min=53, tm_sec=59, tm_wday=0, tm_yday=315, tm_isdst=-1)
datetime obj转换为其它
datetime obj 转换为其它类型,用的都是 datetime 的函数。
初始化:
dt_obj = datetime.datetime(2008, 11, 10, 17, 53, 59)
dt obj —> string
date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")
dt obj —> time obj
time_tuple = dt_obj.timetuple()
time obj转换为其它
初始化:
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
time obj —> string
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
time obj —> datetime obj
datetime.datetime(*time_tuple[0:6])
time obj —> timestamp
ts = time.mktime(time_tuple)
timestamp转换为其它
初始化: timestamp = 1226527167.595983
!!注意以下两种都使用local时区
timestamp —> dt obj
dt_obj = datetime.fromtimestamp(timestamp)
timestamp —> time obj
time_tuple = time.localtime(timestamp)
!!以下两种方式和时区相关,比较标准时区时间和本地时区时间
使用UTC —> dt obj
#本地时区时间
>>> datetime.datetime.fromtimestamp(tm)
datetime.datetime(2012, 12, 17, 23, 39, 58, 401881)
#标准时区时间
>>> datetime.datetime.utcfromtimestamp(tm)
datetime.datetime(2012, 12, 17, 15, 39, 58, 401881)
使用UTC —> time obj
#本地时区时间
>>> time.localtime(tm)
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=17, tm_hour=23, tm_min=39, tm_sec=58, tm_wday=0, tm_yday=352, tm_isdst=0)
#标准时区时间
>>> time.gmtime(tm)
time.struct_time(tm_year=2012, tm_mon=12, tm_mday=17, tm_hour=15, tm_min=39, tm_sec=58, tm_wday=0, tm_yday=352, tm_isdst=0)